I have a textbox that posts info to the server and it’s in JSON format. Lets say I want to enter two quotes for the value, and the JSON struct would look like:
{
"test": """"
}
I need it to look like:
{
"test": "\"\""
}
so it will follow JSON standards and can be parsable/stringifyable.
I tried using
var val = myVal.replace('"', "\\\"");
but this didn’t work. val ends up with only one escaped quote like so \""Any help is much appreciated!
My answer makes some assumptions, as I’ve had to fill in the rather sizeable gaps in your question:
If I’ve got that right, let’s proceed…
Baseline code
So, with some placeholders, you’re doing:
Live demo, showing the malformed JSON.
Initial attempt
To ensure that
JSONis valid, escape any quotes and backslashes that it may contain. You already gave it a go:and the result of your attempt is:
Only the first quote has been escaped. This is because only one instance of the search string is replaced by default.
The Mozilla documentation says:
Working attempt
Unfortunately, the
flagsparameter is non-standard, so let’s switch to the regex version ofreplace, and use the/gswitch in it:(You’ll notice that I also condensed the replacement string, for brevity.)
Result:
Live demo. Hurrah!
Complete solution
Let’s also add logic to escape backslashes, and we end up with this:
Result:
Live demo.