Escape single quotes in JSON.stringify
Solution 1
This should get the single quote to be displayed in the browser:
var final_string = JSON.stringify(context).replace(/[\/\(\)\']/g, "'");
Solution 2
I solved my issue with the following helper
function json(context) {
return JSON.stringify(context).replace(/[\/\(\)\']/g, "\\$&");
}
I.e., the escape must be done after the stringification.
João Pimentel Ferreira
Updated on June 04, 2022Comments
-
João Pimentel Ferreira almost 2 years
I know, I don't need it, but I think I actually do.
I want to have a valid JS code rendered by
handlebarsjs
before it is even rendered. The JS minification tools just minify valid JS files and minifying on the fly increases processing time. This is the JS handlebars code.var stringsObj = JSON.parse('{{{ json stringsDataObj }}}');
As you see, the single quotes up-there make that line of code a valid JS code. The
handlebars
helper is:function json(context) { return JSON.stringify(context); }
And what's the problem? Well, some of the items in
stringObj
happen to have single quotesstringsDataObj = { "str1": "I'm here", "str2": "You're there" }
and when it rendes
var stringsObj = JSON.parse('"str1": "I'm here", "str2": "You're there"');
gives an JS error
Is there a way to escape also single quotes in JSON.stringify? I tried with a replacer function, but without success.