5

What is the difference between

var regEx = /\d/;

and

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

Bob

0

1 Answer 1

8

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the explaination, the reason I asked was I had this expression /^ +|[\\/#;]| +$/gi (1 or more spaces OR contains \ / # ; OR ends with one or more space). When using the non-constructor every odd time the result resulted in false. Eg. the result was alternating. When using the constructor everything worked as expected every time. Strange!
There is yet another difference: The literal only creates one object at parse time whereas the constructor function always creates a new object. This will be changed though in ES5 and the literal will also always return a new object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.