用于Javascript正则表达式的转义字符串

用于Javascript正则表达式的转义字符串,javascript,regex,escaping,Javascript,Regex,Escaping,可能重复: 我正在尝试基于用户输入构建javascript正则表达式: function FindString(input) { var reg = new RegExp('' + input + ''); // [snip] perform search } 函数查找字符串(输入){ var reg=新的RegExp(“”+输入+“”); //[snip]执行搜索 } 但是,当用户输入包含?或*时,正则表达式将无法正常工作,因为它们被解释为正则表达式特殊值。事实上,如果用户在

可能重复:

我正在尝试基于用户输入构建javascript正则表达式:

function FindString(input) { var reg = new RegExp('' + input + ''); // [snip] perform search } 函数查找字符串(输入){ var reg=新的RegExp(“”+输入+“”); //[snip]执行搜索 } 但是,当用户输入包含
*
时,正则表达式将无法正常工作,因为它们被解释为正则表达式特殊值。事实上,如果用户在字符串中放入不平衡的
[
),则正则表达式甚至无效

什么是javascript函数来正确转义所有特殊字符以用于正则表达式?

Short'n Sweet 示例

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
注意:上面的答案不是原始答案;它是经过编辑以显示的。这意味着它与下面npm中的代码不匹配,也与下面的长答案中显示的不匹配。注释现在也令人困惑。我的建议是:使用上面的答案,或者从MDN获取它,忽略此ans的其余部分wer.-达伦,2019年11月)

安装

可在npm上作为

注意

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

其他符号(~`!@#…)可以转义而不产生任何后果,但不要求转义

测试用例:一个典型的url 长话短说 如果你要使用上面的函数,至少在你的代码文档中链接到这个堆栈溢出帖子,这样测试伏都教看起来就不会太难了

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")
}());
var-escapeRegExp;
(功能(){
//请参阅以下表格:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
//这些字符应该转义
// \ ^ $ * + ? . ( ) | { } [ ]
//这些字符仅在括号内具有特殊含义
//他们不需要逃脱,但他们可以逃脱
//无任何不良影响(据我所知,并进行了随机测试)
// : ! , = 
//我的测试“~!@$%^&*({}[]`/=?+\\\\\\-\\:'\”,“。匹配(/[\\\\\]/g)
变量特殊值=[
//订购这些物品
"-"
, "["
, "]"
//顺序对这些都不重要
, "/"
, "{"
, "}"
, "("
, ")"
, "*"
, "+"
, "?"
, "."
, "\\"
, "^"
, "$"
, "|"
]
//我选择用“\”转义每个字符
//即使只有一些人在[]内严格要求
,regex=RegExp('['+specials.join('\\')+']',g')
;
escapeRegExp=函数(str){
返回str.replace(regex,\\$&);
};
//test escapeRegExp(“/path/to/res?search=this.that”)
}());

Wow,太详细了。我更喜欢。但是任何不需要转义的东西……为什么它被“\\$&”替换。这是什么意思?对不起,我是JS新手。@SushantGupta“\\”添加了新的反斜杠,它转义匹配的特殊正则字符。The”$&“是对当前模式匹配内容的反向引用,添加了原始的特殊正则字符。这些字符中的大多数不需要在字符类中转义。破折号和正斜杠根本不需要转义。因此,这可以简化为:return str.replace(/[{}()*+?^$\\]\.\\]/g,\\$&”);2016年是否有更明智的方法?Lodash具有escapeRegExp专用功能:
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")
}());