[英]Matching literal special characters in javascript regex
For some reason this: 由于某种原因:
RegExp('\*').test($var)
gives the following error: 给出以下错误:
SyntaxError: Invalid regular expression: /*/: Nothing to repeat
It looks like the engine doesn't like how I escaped the special character. 引擎似乎不喜欢我如何逃脱特殊字符。 Is this not the correct way of escaping?
这不是逃脱的正确方法吗?
You are trying to match a literal asterisk, but in fact you are applying a *
quantifier on the start of string since there is only 1 slash in your regex that is not enough to escape the asterisk for the regex engine. 您试图匹配文字星号,但实际上您在字符串的开头应用了
*
量词,因为正则表达式中只有1个斜杠不足以为正则表达式引擎转义星号。
Use 采用
/\*/.test($var);
Or 要么
RegExp('\\*').test($var)
However, the literal notation is preferred since you are not building the regexp pattern dynamically (ie the pattern is known at design-time). 但是,首选文字表示法,因为您不是动态构建正则表达式模式(即,在设计时就知道该模式)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.