简体   繁体   English

用Javascript替换引号?

[英]Replacing quotation marks in Javascript?

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. 因为我将成为document.writing字符串,所以需要将它们更改为撇号或转义。 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. 我该怎么做,因为当我尝试它似乎不起作用,特别是我认为因为字符串的引号会停止脚本的其余部分工作。

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! 谢谢!

Escaping them for HTML: 为HTML转义它们:

var escapedString = string.replace(/'/g, "'").replace(/"/g, """);

Escaping them for JS code: 为JS代码转义它们:

var escapedString = string.replace(/(['"])/g, "\\$1");

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)   

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. 因此,如果源字符串具有单引号,请使用斜杠和单引号替换每个单引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM