How to Replace " with \" in Javascript

How to Replace " with \" in Javascript

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!

5

4 Answers

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.


Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.