Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript replace double quotes with slash

Tags:

javascript

I want to replace " with \" with Javascript.

I have:

text = text.toString().replace("\"", '\\"')

The result:

\\"
like image 212
badc0re Avatar asked Jul 05 '12 14:07

badc0re


4 Answers

Try this:

text = text.toString().replace(/"/g, '\\"') 

Or this:

text = text.toString().replace('"', '\\"') 
like image 76
antyrat Avatar answered Oct 04 '22 14:10

antyrat


I have a small suggestion based on antyrat's answer.

text = text.toString().replace(/\\"/g, '"').replace(/"/g, '\\"'); 

This extra step will replace all the \" to " first, and then replace all the " back to \". It will help when your current string contains a combination of \" and ", especially when the string is a result from JSON.stringify()

like image 20
EvilDuck Avatar answered Oct 04 '22 13:10

EvilDuck


This will do:

text = text.toString().replace("\"", '\\\"');

You basically have to escape both '\' and '"' by \

like image 37
Anshul Avatar answered Oct 04 '22 13:10

Anshul


var text = JSON.stringify(JSON.stringify(text))

like image 30
Masoud Avatar answered Oct 04 '22 15:10

Masoud