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!"
(注意:以上不是原始答案;它经过编辑以显示one from MDN。这意味着它确实不与您在下面的 npm 中的代码,并且 not 与下面的长答案中显示的匹配。cmets 现在也很混乱。我的建议:使用上面的,或者从 MDN 获取它,而忽略其余的这个答案。-Darren,2019 年 11 月)
安装
在 npm 上可用 escape-string-regexp
npm install --save escape-string-regexp
注意
见MDN: Javascript Guide: Regular Expressions
其他符号 (~`!@# ...) 可以转义而不会产生任何后果,但不是必须的。
.
.
.
.
测试用例:一个典型的url
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")
}());