Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 677
Darcy Avatar asked Aug 12 '11 18:08

Darcy


1 Answers

Use this

var val = myVal.replace(/"/g, '\\"');
like image 179
Mrchief Avatar answered Sep 23 '22 15:09

Mrchief