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
2 Answers
Reset to default 7There 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.