本文翻译自:Escape string for use in Javascript regex [duplicate]
Possible Duplicate: 可能重复:
Is there a RegExp.escape function in Javascript? Javascript中是否存在RegExp.escape函数?
I am trying to build a javascript regex based on user input: 我正在尝试根据用户输入构建javascript正则表达式:
function FindString(input) { var reg = new RegExp('' + input + ''); // [snip] perform search }
But the regex will not work correctly when the user input contains a ?
但是,当用户输入包含?
时,正则表达式将无法正常工作?
or *
because they are interpreted as regex specials. 或*
因为它们被解释为正则表达式特殊项。 In fact, if the user puts an unbalanced (
or [
in their string, the regex isn't even valid. 实际上,如果用户在字符串中输入不平衡(
或[
,则正则表达式甚至无效。
What is the javascript function to correctly escape all special characters for use in regex? 什么是可以正确转义要在正则表达式中使用的所有特殊字符的javascript函数?
#1楼
参考:https://stackoom.com/question/ESVO/在Javascript正则表达式中使用的转义字符串-重复
#2楼
Short 'n Sweet 短'n甜
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
Example 例
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
( NOTE : the above is not the original answer; it was edited to show the one from MDN . This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019) ( 注 :上面是不是原来的答案,它被编辑以显示从MDN一个 ,这意味着它不匹配您将在下面NPM的代码查找,并且不匹配什么是在下面长所示。我的建议:使用上面的内容,或从MDN中获取它,然后忽略此答案的其余部分。-Darren,Nov 2019)
Install 安装
Available on npm as escape-string-regexp 在npm上可以作为转义字符串-regexp使用
npm install --save escape-string-regexp
Note 注意
See MDN: Javascript Guide: Regular Expressions 请参见MDN:Javascript指南:正则表达式
Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be. 其他符号(〜`!@#...)可以不加任何含义地转义,但不是必须的。
. 。
. 。
. 。
. 。
Test Case: A typical url 测试案例:一个典型的URL
escapeRegExp("/path/to/resource.html?search=query");
>>> "\/path\/to\/resource\.html\?search=query"
The Long Answer 长答案
If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo. 如果要使用上面的函数,请至少链接到代码文档中的此堆栈溢出文章,以使它看起来像疯狂的难以测试的伏都教。
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")
}());