Javascript中对字符串进行正则转义 - js字符串转义-正则表达式1

在Javascript正则表达式中使用的转义字符串[重复]

本文翻译自:Escape string for use in Javascript regex [duplicate]

This question already has answers here : 这个问题已经在这里有了答案 :

Closed 7 years ago . 7年前关闭。

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

转载于:https://blog.csdn.net/w36680130/article/details/105912893

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值