My answer makes some assumptions, as I've had to fill in the rather sizeable gaps in your question:
- The user will enter a text string into a textbox;
- Your script will read the textbox contents, and use those contents as the value of one of the items in a JSON string that it's building;
- The script sends this resulting JSON string to the server somehow.
If I've got that right, let's proceed...
Baseline code
So, with some placeholders, you're doing:
function get_contents_of_textbox() {
// Dummy data for example
return 'My mum pushed and I said "Hello World"!';
}
function send_to_server(json_str) {
// Dummy action: display JSON string
console.log(json_str);
}
var myVal = get_contents_of_textbox();
var JSON = '{ "test": "' + myVal + '" }';
send_to_server(JSON);
Live demo, showing the malformed JSON.
Initial attempt
To ensure that JSON is valid, escape any quotes and backslashes that it may contain. You already gave it a go:
myVal = myVal.replace('"', "\\\"");
and the result of your attempt is:
{ "test": "My mum pushed and I said \"Hello World"!" }
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:
To perform a global search and replace, either include the g flag in
the regular expression or if the first parameter is a string, include
g in the flags parameter.
Working attempt
Unfortunately, the flags parameter is non-standard, so let's switch to the regex version of replace, and use the /g switch in it:
myVal = myVal.replace(/"/g, '\\"');
(You'll notice that I also condensed the replacement string, for brevity.)
Result:
{ "test": "My mum pushed and I said \"Hello World\"!" }
Complete solution
Let's also add logic to escape backslashes, and we end up with this:
function get_contents_of_textbox() {
// Dummy data for example
return 'My mum pushed [a back\\slash] and I said "Hello World"!';
}
function send_to_server(json_str) {
// Dummy action: display JSON string
console.log(json_str);
}
var myVal = get_contents_of_textbox();
myVal = myVal.replace(/\\/g, '\\\\'); // escape backslashes
myVal = myVal.replace(/"/g, '\\"'); // escape quotes
var JSON = '{ "test": "' + myVal + '" }';
send_to_server(JSON);
Result:
{ "test": "My mum pushed [a back\\slash] and I said \"Hello World\"!" }