First of all: I know that there are many questions related to escaping, but I did not found a generally working answer so far. Say I have this simple toy function for demonstration:
function f(somePOJO) {
var s = eval("'" + JSON.stringify(somePOJO) + "';"); // for demonstration only
return JSON.parse(s);
}
const clone = f({a: 1, b: "c"});
Given an object literal such as {a: 1, b: "c"} (a POJO), f should return a "clone" of it. (Note that I do not really use this approach for cloning or similar, and I am aware that eval is evil and also that it is not even needed here, it's just for demonstration of the escaping problem!)
This works fine, but only as long as the POJO values do not contain a '. Now of course I could escape the JSON by using something like JSON.stringify(somePOJO).replace(/'/g, "\\'"). This works if the POJO values contain ', but not if they contain \\'. And this creates a spiral of escaping...
Is there a solution to this at all?
stringifyprovides an optional second function parameter which you could use to sanitise your values.