Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Regex Compile()

Is there a shorter way to write this?

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

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

like image 242
JamesBrownIsDead Avatar asked Feb 12 '10 01:02

JamesBrownIsDead


1 Answers

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.

like image 184
Todd Moses Avatar answered Oct 01 '22 22:10

Todd Moses