I want to replace "
with \"
with Javascript.
I have:
text = text.toString().replace("\"", '\\"')
The result:
\\"
Try this:
text = text.toString().replace(/"/g, '\\"')
Or this:
text = text.toString().replace('"', '\\"')
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()
This will do:
text = text.toString().replace("\"", '\\\"');
You basically have to escape both '\' and '"' by \
var text = JSON.stringify(JSON.stringify(text))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With