Replacing quotation marks in Javascript?

谁都会走 提交于 2019-12-05 21:42:27

问题


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.

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!


回答1:


Escaping them for HTML:

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

Escaping them for JS code:

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



回答2:


If you are generating Javascript strings on the server, you will need to escape quotes and certain other characters.

\'      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)   



回答3:


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.



来源:https://stackoverflow.com/questions/2351576/replacing-quotation-marks-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!