如果模式在javascript或jQuery中匹配,如何附加反斜杠

时间:2014-09-23 02:53:13

标签: javascript jquery regex

我必须检查一个字符串是否包含某个特殊字符,如果是,请为其添加一个反斜杠。

var spChar=['%','^','!'];

如果字符串为"This contains % and ^ characters".
我想成功"This contains \% and \^ characters".

我不想循环遍历所有角色。无论如何,我可以通过使用正则表达式来实现这一点

1 个答案:

答案 0 :(得分:5)

你可以使用像

这样的正则表达式
"This contains % and ^ characters".replace(/([%^!])/g, '\\$1')

但如果你期待escape regex,你可以使用像

这样的功能
if (!RegExp.escape) {
    RegExp.escape = function (s) {
        return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
    };
}

//then
var newstring = RegExp.escape(mystring)