I'm attempting to replace single quotation marks in the values of my JSON string with \' however, it seems to not be working when I try to use the replacer function.
var myObj = {
test: "'p'"
}
var replacer = function (key, value) {
if (typeof value === 'string')
return value.replace(/'/g, "\\'");
else return value;
};
var JSONstring = JSON.stringify(myObj, replacer, ' ');
alert(JSONstring);
https://jsfiddle.net/4fsqozek/1/
However, when I simply do a replace after creating the string without using the replacer function like this:
var JSONstring = JSON.stringify(myObj).replace(/'/g, "\\'");
The regular expression I used works perfectly fine.
EDIT - clarification - when using the replacer function, the output value contains double backslashes like this \\'p\\' , which is not the expected outcome.
Can someone provide an explanation for this?