Darcy
Darcy

Reputation: 5368

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!

Upvotes: 10

Views: 56765

Answers (4)

Mrchief
Mrchief

Reputation: 76198

Use this

var val = myVal.replace(/"/g, '\\"');

Upvotes: 7

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

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\"!" }

Live demo. Hurrah!


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\"!" }

Live demo.

Upvotes: 15

Endophage
Endophage

Reputation: 21463

As you said you're getting the string from a textbox you don't need to do anything to it to get it back to the server. If you get the value of the textbox via jQuery's $() notation or pure document.getElementById it will already be properly escaped. JavaScript doesn't take the value of your textbox and try to put it in quotes.

If you text box has "" entered into it, document.getElementById('mytextbox').value is not equal to "\"\"". The backslashes are only necessary when you are defining a string literal.

Try removing all your escaping and regex replacing and just send back the data from the text box without doing anything to it. Your json should look something like:

{
    "test" : document.getElementById('myTextBox')
}

Upvotes: 0

Marc B
Marc B

Reputation: 360572

Just create a JS array

var arr = {
   test: '""'
}

and let the JSON interface handle the escaping for you. You shouldn't ever have to deal with the details yourself.

Upvotes: 0

Related Questions