How to encode non-ASCII characters as \uXXXX sequences in express/jade
escaping, express, node.js, pug, unicode
Solution
JSON.stringify(["ä", "ä"]).replace(/[\u0080-\uFFFF]/g, function(m) {
return "\\u" + ("0000" + m.charCodeAt(0).toString(16)).slice(-4);
});
//["\u00e4","\u00e4"]
JSON.stringify([{title: "ä"}, {title: "ä"}]).replace(/[\u0080-\uFFFF]/g, function(m) {
return "\\u" + ("0000" + m.charCodeAt(0).toString(16)).slice(-4);
});
//[{"title":"\u00e4"},{"title":"\u00e4"}]
Although this is completely useless and it eats CPU for nothing to provide larger responses :/ Remember that each CPU cycle used in node.js is a CPU cycle where the entire server is down unless you cluster.
Problem
I have the following express route: ``` var data = [ { id: 1, title: 'aide-memoire' }, { id:2, title: 'apres moi' } ]; app.get('/', function (req, res) { res.render('photo/list', { data: data }); }); ``` In my JADE template I'm getting that data like the following: ``` !!!5 html head body script var data = !{JSON.stringify(calculates)}; ``` But I get that data array on a client like this: ``` <!DOCTYPE html> <html> <head></head> <body> <script type="text/javascript"> var data = [ { "id":1, "title": 'aide-memoire'}, { "id":2, "title": 'apres moi'} ]; </script> </body> </html> ``` But I need to encode non-ASCII characters as \uXXXX sequences like the following: ``` [ {"id":1, "title": "aide-m%E9moire"}, {"id":2, "title": "apr%E8s%20moi"} ] ``` How can I do that in express/jade?