Javascript Regex not working on script but working on console

Viewed 5846

I'm trying to validate only 4 numbers like this:

Regex

It is working on the above page, but when I use it on a script it is not working:

var reg = new RegExp('^\d{4}$/');
reg.test(1234);
reg.test('1234');

Both are returning false...

If I test on the browser console like this:

/^\d{4}$/.test('1234');
/^\d{4}$/.test(1234);

Both are returning true.

What I'm missing?

1 Answers

The problem is because your RegExp is not initialized properly.

You can either do:

// Note the \\ to escape the backslash
var reg = new RegExp('^\\d{4}$');

Or

var reg = new RegExp(/^\d{4}$/);
Related