1

While researching the use of regular expressions in javascript, one can encounter examples of two types:

A:

var regex = /^[a-zA-Z0-9]+$/;

B:

var regex = new RegExp ("^[a-zA-Z0-9]*$"); 

Is it necessary to use var foo = new RegExp? Or, when should one pick each method?

Roy
  • 1,307
  • 1
  • 13
  • 29

3 Answers3

6

The RegExp() constructor is useful when you have to assemble a regular expression dynamically at run time. If the expression is completely static, it's easier to use the native regex syntax (your "A"). The ease-of-use of the native syntax stems from the fact that you don't have to worry about quoting backslashes, as you do when your regular expression begins life as a string constant.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • In addition, an important difference is when the expression is compiled (at evaluation vs. run-time) which may be expensive when dealing with large datasets and/or many regular expressions. – marekful Feb 21 '13 at 19:50
  • @MarcellFülöp that's a good point; I don't know how much of a difference it makes in modern JavaScript engines. I think there used to be an explicit ".compile()" function, but that's been deprecated for a long time. – Pointy Feb 21 '13 at 20:16
1

Is it necessary to use var foo = new RegExp?

No, obviously not. The other one works as well.

Or, when should one pick each method?

Regex literals are easier to read and write as you do not need to string-escape regex escape characters - you can just use them (backslashes, quotes). Also, they are parsed only once during script "compilation" - nothing needs to be executed each time you the line is evaluated.

The RegExp constructor only needs to be used if you want to build regexes dynamically.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

Here's an example of a 'dynamic' regular expression where you might need new RegExp.

var search = 'dog',
    re = new RegExp('.*' + search + '.*');

If it's a static regular expression, then the literal syntax (your A option) is better because it's easier to write and read.

Trevor Dixon
  • 23,216
  • 12
  • 72
  • 109