转义字符串用于Javascript正则表达式 [英] Escape string for use in Javascript regex
问题描述
可能重复:
在Javascript中是否有RegExp.escape函数?
我正在尝试根据用户输入构建一个JavaScript正则表达式:
函数FindString(input){
var reg = new RegExp(''+ input +'');
// [snip]执行搜索
}
但是当用户输入包含正则表达式将无法正常工作一个?
或 *
,因为它们被解释为正则表达式特效。实际上,如果用户在其字符串中放置了一个不平衡的(
或 [
],则该正则表达式甚至无效。
什么是正确转义用于正则表达式的所有特殊字符的javascript函数?
Short'n Sweet
function escapeRegExp(str){
return str.replace(/ [\-\ [\] \ / \ {\} \(\)\ * \ + \ \.\\\ ^ \ $ \?| ] / g,\\ $&);
}
strong>示例
escapeRegExp(所有这些都应该转义:\ ^ $ * +? )| {} []);
>>>所有这些应该被转义:\\ \ ^ \ $ \ * \ + \? \。\(\)\ | \ {\} \ [\]
安装
在npm可用 escape-string-regexp
npm install --save escape-string-regexp
注意 p>
其他符号(〜`!@#...)可以没有后果而被转义,但不是必须的。 p>
。
。
。
测试用例:典型的URL
escapeRegExp( /路径/到/ resource.html搜索查询=?);
>>> \ / path\ / to\ / resource\.html\??search = query
长答案
如果您要使用上述功能,至少链接到代码文档中的此堆栈溢出文件,以使其不会像疯狂的难以测试的巫术。
var escapeRegExp;
(function(){
//参考这里的表:
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
//这些字符应该被转义
// \ ^ $ * +?。()| {} []
//这些字符在括号内只有特殊含义
//他们不需要被转义,但是它们可能被转义为
//,没有任何不利影响(尽我所知和随意测试)
//:!,=
//我的测试〜!@#$%^& *(){} []`/ =?+ \ | -_ ;:'\,& \#] / g)
var specials = [
//订购这些
的事项 -
,
, ]
//订单对于这些
中的任何一个都不重要,/
,{
,}
,(
,*
,+
,?
,
,\\
,^
,$
,|
]
//我选择用'\'
//转义每个字符,即使只有一些严格要求它在[]
,regex = RegExp('['+ specials.join('\\')+']','g')
;
escapeRegExp = function(str){
return str.replace(regex,\\ $&);
};
// test escapeRegExp(/ path / to / res?search = this.that)
}());
Possible Duplicate:
Is there a RegExp.escape function in Javascript?
I am trying to build a javascript regex based on user input:
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?
Short 'n Sweet
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
Example
escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");
>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "
Install
Available on npm as escape-string-regexp
npm install --save escape-string-regexp
Note
See MDN: Javascript Guide: Regular Expressions
Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.
.
.
.
.
Test Case: A typical 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")
}());
这篇关于转义字符串用于Javascript正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!