最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript Regex Compile() - Stack Overflow

programmeradmin2浏览0评论

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.

发布评论

评论列表(0)

  1. 暂无评论