bob
bob

Reputation: 73

JavaScript RegExp Differences

What is the difference between

var regEx = /\d/;

and

var regEx = new RegEx("\d");

Bob

Upvotes: 5

Views: 911

Answers (1)

meder omuraliev
meder omuraliev

Reputation: 186562

Both evaluate to be the same exact regex, but the first is a literal, meaning you cannot use any variables inside it, you cannot dynamically generate a regex.

The second uses the constructor explicitly and can be used to create dynamic regular expressions.

var x = '3', r = ( new RegExp( x + '\d' ) ); r.test('3d')

The above is an example of dynamically constructing the regex with the constructor, which you can not do in literal form.

In 99% of cases you will just rely on the first version ( literal ) for all your regexpes in JS. In an advanced scenario where you need say, user input to dynamically construct a regex then that's when you'll need the second form.

EDIT #1: The first matches a digit, the second just matches the letter d. You have to double-escape the second one in order for it to equal the first one, which I assume you meant to do. Just remember the advice I typed above is accurate if the second example is new RegExp('\\d').

/\d/.test('3') // true
( new RegExp('\d') ).test('3') // false
( new RegExp('\\d') ).test('3') // true

Upvotes: 8

Related Questions