替换 Javascript 中的引号?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2351576/
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
Replacing quotation marks in Javascript?
提问by James Wanchai
For a web app I'm making, I'm going to be getting text strings coming in, occasionally which contain quotation marks. Because I am then going to be document.writing the string, they need to be changed either into apostrophes or escaped. How would I do that, because when I try it doesn't seem to work, specifically I think because the string's quotation marks stop the rest of the script working.
对于我正在制作的网络应用程序,我将收到文本字符串,偶尔会包含引号。因为我将要使用 document.writing 字符串,所以需要将它们更改为撇号或转义。我该怎么做,因为当我尝试时它似乎不起作用,特别是我认为是因为字符串的引号会阻止脚本的其余部分工作。
Hope that makes some sense, I'm quite new to this so that's why it might not make sense. I'll try and clarify if need be. Thank you!
希望这是有道理的,我对此很陌生,所以这就是为什么它可能没有意义。如果需要,我会尝试澄清。谢谢!
回答by Eli Grey
Escaping them for HTML:
为 HTML 转义它们:
var escapedString = string.replace(/'/g, "'").replace(/"/g, """);
Escaping them for JS code:
将它们转义为 JS 代码:
var escapedString = string.replace(/(['"])/g, "\");
回答by Lachlan Roche
If you are generating Javascript strings on the server, you will need to escape quotes and certain other characters.
如果您在服务器上生成 Javascript 字符串,则需要对引号和某些其他字符进行转义。
\' Single quotation mark
\" Double quotation mark
\ Backslash
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Horizontal tab
\ddd Octal sequence (3 digits: ddd)
\xdd Hexadecimal sequence (2 digits: dd)
\udddd Unicode sequence (4 hex digits: dddd)
回答by Thomas
You need to escape them like so:
你需要像这样逃避他们:
var foo = '\'foo\'';
So, if the source string has single quotes, replace each single quote with a slash and a single quote.
因此,如果源字符串有单引号,请将每个单引号替换为斜杠和单引号。

