Some assumptions were made in my answer, since I had to fill in quite significant gaps in your question:
- The user enters a text string into a text field;
- Your script will read the contents of the text field and use this content as the value of one of the elements of the JSON string that it creates;
- The script sends this received JSON string to the server in some way.
If I succeed, let me continue ...
Source
So with some placeholders you do:
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 wrong JSON.
Initial attempt
To ensure that JSON valid, avoid any quotation marks or backslashes that may contain. You have already given it:
myVal = myVal.replace('"', "\\\"");
and the result of your attempt :
{ "test": "My mum pushed and I said \"Hello World"!" }
Only the first quote was screened. This is because by default only one instance of the search string is replaced.
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 go to the replace regular expression version and use the /g switch in it:
myVal = myVal.replace(/"/g, '\\"');
(You will notice that I also shortened the replacement string for short.)
Result:
{ "test": "My mum pushed and I said \"Hello World\"!" }
Complete solution
Let it also add logic to discard backslashes, and in the end we get:
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\"!" }