I'm trying to replace single quotes in my json string values with \' however it is not working only 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 if I do just a simple replace after the string is created like this without using the replacer function
var JSONstring = JSON.stringify(myObj).replace(/'/g, "\\'");
The regex I used works fine.
EDIT - clarification - using replacer function the output value contains double backslash like this \\'p\\' , which is not what I'm expecting
Can anyone explain this?