Escaping quotes in a javascript string

无人久伴 提交于 2019-12-20 04:53:08

问题


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:


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/



来源:https://stackoverflow.com/questions/11334489/escaping-quotes-in-a-javascript-string

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