The function linked above is insufficient.(上面链接的功能不足。)
It fails to escape ^
or $
(start and end of string), or -
, which in a character group is used for ranges.(它无法转义^
或$
(字符串的开头和结尾)或-
,这在字符组中用于范围。)
Use this function:(使用此功能:)
RegExp.escape= function(s) {
return s.replace(/[-/\^$*+?.()|[]{}]/g, '\$&');
};
While it may seem unnecessary at first glance, escaping -
(as well as ^
) makes the function suitable for escaping characters to be inserted into a character class as well as the body of the regex.(乍看起来似乎没有必要,但转义-
(以及^
)使该函数适合于转义要插入字符类和正则表达式主体的字符。)
Escaping /
makes the function suitable for escaping characters to be used in a JS regex literal for later eval.(转义/
使该函数适合转义要在JS regex文字中使用的字符,以供以后评估。)
As there is no downside to escaping either of them it makes sense to escape to cover wider use cases.(由于逃避任何一个都没有不利之处,因此有理由逃避以涵盖更广泛的用例。)
And yes, it is a disappointing failing that this is not part of standard JavaScript.(是的,如果它不是标准JavaScript的一部分,这是令人失望的。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…