我正在尝试根据用户输入构建一个javascript正则表达式:
function FindString(input) { var reg = new RegExp('' + input + ''); // [snip] perform search }
但是当用户输入包含?
或*
时,正则表达式将无法正常工作,因为它们被解释为正则表达式特殊符号。实际上,如果用户在其字符串中放置了不平衡(
或[
,则正则表达式甚至无效。
正确转义用于正则表达式的所有特殊字符的javascript函数是什么?
答案 0 :(得分:889)
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
示例强>
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
安装强>
在{n}上以escape-string-regexp
的形式提供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")
}());