What is the difference between
var regEx = /\d/;
and
var regEx = new RegEx("\d");
Bob
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With