Escaping quotes in a javascript string

2020-04-28 06:32发布

I'm trying to escape the quotes (and apostrofes and escape char) in a text string in 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 /..

I just can't seem to get this working and don't know what's wrong.

Here's a JSFiddle: http://jsfiddle.net/hvtgf/

1条回答
我只想做你的唯一
2楼-- · 2020-04-28 07:25

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/

查看更多
登录 后发表回答