转义string在Javascript正则expression式中使用

可能重复:
Javascript中是否有RegExp.escape函数?

我想build立一个基于用户input的JavaScript正则expression式:

函数FindString(input){
     var reg = new RegExp(''+ input +'');
     // [snip]执行search
 }

但是,当用户input包含一个正则expression式时,正则expression式将无法正常工作?*因为它们被解释为正则expression式特殊。 事实上,如果用户放置一个不平衡的([在他们的string,正则expression式甚至不是有效的。

什么是javascript函数来正确地转义在正则expression式中使用的所有特殊字符?

简短甜美

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

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

安装

可用于npm作为escape-string-regexp

 npm install --save escape-string-regexp 

注意

请参阅MDN:Javascript指南:正则expression式

其他符号(〜`!@#…)可以无后果地逃脱,但不是必须的。

testing用例:一个典型的url

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

长的答案

如果你打算使用上面的函数,至less在你的代码的文档中链接到这个堆栈溢出文章,以便它看起来不像疯狂的难以testing的巫术。

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