JavaScript RegExp Differences

What's the difference between

var regEx = /\d/;

and

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

Bean

+5
source share
1 answer

Both are evaluated as the same exact regular expression, but the first is a literal, that is, you cannot use any variables inside it, you cannot dynamically generate a regular expression.

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 example is the dynamic construction of a regular expression with a constructor that you cannot do in literal form.

99% () JS. , , , .

№ 1: , d. , , , , . , , RegExp ('\ d').

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

All Articles