开发者

JavaScript Regex Compile()

开发者 https://www.devze.com 2022-12-20 02:58 出处:网络
Is there a shorter way to write this? var needed = /\\$\\[\\w+\\]/mi; needed.compile(/\\$\\开发者_StackOverflow中文版[\\w+\\]/mi);

Is there a shorter way to write this?

var needed = /\$\[\w+\]/mi;
needed.compile(/\$\开发者_StackOverflow中文版[\w+\]/mi);

Why do I have to pass the pattern back into the regex when I've already declared it in the first line?!


There are two ways of defining regular expressions in JavaScript — one through an object constructor and one through a literal. The object can be changed at runtime, but the literal is compiled at load of the script, and provides better performance.

var txt=new RegExp(pattern,modifiers);

or more simply:

var txt=/pattern/modifiers; 

This is the same thing that cobbai is saying. In short, you do not have to do both.


from MDC:

The literal notation provides compilation of the regular expression when the expression is evaluated

so /\$\[\w+\]/mi is a compiled regex already.

0

精彩评论

暂无评论...
验证码 换一张
取 消