Short 'n Sweet(2021年更新)
要转义正则表达式本身:
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
转义替换字符串:
function escapeReplacement(string) {
return string.replace(/\$/g, '$$$$');
}
例
所有转义的正则表达式字符:
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
查找并替换字符串:
var haystack = "I love $x!";
var needle = "$x";
var safeNeedle = escapeRegExp(needle); // "\\$x"
var replacement = "$100 bills"
var safeReplacement = escapeReplacement(replacement); // "$$100 bills"
haystack.replace(
new RegExp(safeNeedle, 'g'),
escapeReplacement(safeReplacement),
);
// "I love $100 bills!"
(注:以上不是原来的答案;它被编辑以显示来自MDN的那个。这意味着它与您在下面的npm的代码中找到的内容不匹配,并且与下面的长答案中显示的内容不匹配。这些评论现在也令人困惑。我的建议是:使用上面的内容,或者从MDN获取,并忽略这个答案的其余部分。-达伦,2019年11月)
安装
在 npm 上作为转义字符串正则表达式可用
npm install --save escape-string-regexp
注意
参见 MDN: Javascript Guide: Regular Expressions
其他符号 (~'!@# ...)可以逃脱而没有后果,但不是必须的。
.
.
.
.
测试用例:一个典型的网址
escapeRegExp("/path/to/resource.html?search=query");
>>> "\/path\/to\/resource\.html\?search=query"
长答案
如果您要使用上面的函数,请至少链接到代码文档中的此堆栈溢出帖子,以便它不会看起来像疯狂的难以测试的巫毒教。
var escapeRegExp;
(function () {
// Referring to the table here:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
// these characters should be escaped
// \ ^ $ * + ? . ( ) | { } [ ]
// These characters only have special meaning inside of brackets
// they do not need to be escaped, but they MAY be escaped
// without any adverse effects (to the best of my knowledge and casual testing)
// : ! , =
// my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)
var specials = [
// order matters for these
"-"
, "["
, "]"
// order doesn't matter for any of these
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "\\"
, "^"
, "$"
, "|"
]
// I choose to escape every character with '\'
// even though only some strictly require it when inside of []
, regex = RegExp('[' + specials.join('\\') + ']', 'g')
;
escapeRegExp = function (str) {
return str.replace(regex, "\\$&");
};
// test escapeRegExp("/path/to/res?search=this.that")
}());