问题

Possible Duplicate:
Is there a RegExp.escape function in Javascript?

我想根据用户输入建立一个javascript正则表达式:

function FindString(input) {
    var reg = new RegExp('' + input + '');
    // [snip] perform search
}

但是当用户输入包含? * 时,正则表达式将无法正常工作,因为它们被解释为正则表达式特殊.事实上,如果用户在字符串中放置一个不平衡的( [),正则表达式甚至是无效的.

什么是javascript函数以正确转义所有特殊字符以在regex中使用?



解决方法

Short 'n Sweet

function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

示例

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

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

安装

以下列形式提供: escape-string-regexp

npm install --save escape-string-regexp

请注意

请参阅 MDN:Javascript指南:正则表达式 < p>

其他符号(〜`!@#...)可以没有后果地转义,但不一定要.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

如果你打算使用上面的函数,至少链接到这个堆栈溢出帖子在代码的文档,使它看起来不像疯狂的难以测试的巫术.

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")
}());



相关问题推荐