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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3446170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:38:39  来源:igfitidea点击:

Escape string for use in Javascript regex

javascriptregexescaping

提问by too much php

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.

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

What is the javascript function to correctly escape all special characters for use in regex?

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

回答by CoolAJ86

Short 'n Sweet

短甜

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 notmatch what you will find in the code in the below npm, and does notmatch 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,2019 年 11 月)

Install

安装

Available on npm as escape-string-regexp

在 npm 上可用作为转义字符串正则表达式

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