Replacing quotation marks in Javascript?

谁说胖子不能爱 提交于 2019-12-04 03:50:52

Escaping them for HTML:

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

Escaping them for JS code:

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.

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

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