Javascript Javascript用斜杠替换双引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11346963/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript replace double quotes with slash
提问by badc0re
I want to replace "
with \"
with Javascript.
我想更换"
与\"
使用Javascript。
I have:
我有:
text = text.toString().replace("\"", '\"')
The result:
结果:
\"
回答by antyrat
Try this:
尝试这个:
text = text.toString().replace(/"/g, '\"')
Or this:
或这个:
text = text.toString().replace('"', '\"')
回答by Anshul
This will do:
这将:
text = text.toString().replace("\"", '\\"');
You basically have to escape both '\' and '"' by \
您基本上必须通过 \ 转义 '\' 和 '"'
回答by EvilDuck
I have a small suggestion based on antyrat's answer.
我有一个基于 antyrat 的回答的小建议。
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()
这个额外的步骤会先把所有的 \" 替换为 ",然后再把所有的 " 替换回 \"。当您当前的字符串包含 \" 和 " 的组合时,这将有所帮助,尤其是当字符串是 JSON.stringify() 的结果时
回答by Masoud
var text = JSON.stringify(JSON.stringify(text))
var text = JSON.stringify(JSON.stringify(text))