JavaScript Regex Compile() - Stack Overflow

Is there a shorter way to write this?var needed = $[w+]mi;neededpile($[w+]mi);Why do I hav

Is there a shorter way to write this?

var needed = /\$\[\w+\]/mi;
neededpile(/\$\[\w+\]/mi);

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

Is there a shorter way to write this?

var needed = /\$\[\w+\]/mi;
needed.pile(/\$\[\w+\]/mi);

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

Share Improve this question edited Feb 12, 2010 at 1:21 Michael La Voie 27.9k14 gold badges76 silver badges92 bronze badges asked Feb 12, 2010 at 1:11 JamesBrownIsDeadJamesBrownIsDead 4,7156 gold badges33 silver badges30 bronze badges 1
  • 1 If I don't include the pattern again, the regex takes about twice as long. – JamesBrownIsDead Commented Feb 12, 2010 at 1:16
Add a ment  | 

2 Answers 2

Reset to default 7

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 piled 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 pilation of the regular expression when the expression is evaluated

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1743929378a4531525.html

相关推荐

  • JavaScript Regex Compile() - Stack Overflow

    Is there a shorter way to write this?var needed = $[w+]mi;neededpile($[w+]mi);Why do I hav

    2天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信