jQuery:如何使用反斜杠转义单引号和双引号

时间:2021-11-27 20:06:34

I want to escape single and double quotes with a backslash in one line rather than two.

我希望在一行而不是两行中使用反斜杠来转义单引号和双引号。

Example for single quote:

单引号示例:

str = str.replace(/'/g, "\\'");

Is there a way to do this at the same time for double quotes included?

是否有办法同时为双引号括起来?

Sniffer Answered this very well below, and I ended up escaping all characters we needed as follows:

Sniffer在下面回答了这个问题,我最终将我们需要的所有字符转义如下:

str = str.replace(/(['"&:;])/g, "\\$1");

Thanks again Sniffer for the quick response!

再次感谢Sniffer的快速反应!

1 个解决方案

#1


32  

Try this:

尝试这个:

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

#1


32  

Try this:

尝试这个:

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