简体   繁体   English

在javascript字符串中转义引号

[英]Escaping quotes in a javascript string

I'm trying to escape the quotes (and apostrofes and escape char) in a text string in javascript: 我试图在javascript中的文本字符串中转义引号(和撇号和转义字符):

var text = 'Escape " and \' and /.';
var rx = new RegExp('/([\'"])/g');
console.log(text, ' ==> ', text.replace(rx,'//\1'));​​​​​

What I expect to be output is Escape /" and /' and //. , but instead I get Escape " and ' and /. 我希望输出的是Escape /" and /' and //. ,而是我得到Escape " and ' and /. .

I just can't seem to get this working and don't know what's wrong. 我似乎无法让这个工作,不知道什么是错的。

Here's a JSFiddle: http://jsfiddle.net/hvtgf/ 这是一个JSFiddle: http//jsfiddle.net/hvtgf/

Escaping means using backslash \\ but not slash / . 转义意味着使用反斜杠\\但不是斜杠/

However, for your purposes you can try the following: 但是,出于您的目的,您可以尝试以下方法:

text.replace(/([/'"])/g, "/$1");

DEMO: http://jsfiddle.net/hvtgf/1/ 演示: http //jsfiddle.net/hvtgf/1/

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

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