Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript RegExp Differences

What is the difference between

var regEx = /\d/;

and

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

Bob

like image 741
bob Avatar asked Dec 20 '10 20:12

bob


1 Answers

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
like image 85
meder omuraliev Avatar answered Sep 18 '22 19:09

meder omuraliev