Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex not working on script but working on console

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?

like image 448
Albeis Avatar asked Nov 08 '17 16:11

Albeis


People also ask

Why my regex is not working?

You regex doesn't work, because you're matching the beginning of the line, followed by one or more word-characters (doesn't matter if you use the non-capturing group (?:…) here or not), followed by any characters.

Can you use regex in if statement JavaScript?

The RegEx variable can just then be combined with the test( ) method to check the string. As the result is just a returned boolean (true or false), it can be easily combined with an if/else statement or ternary operator to continue with further actions depending on whether the string is present or not.

What is $1 in regex JS?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

Is regex fast JavaScript?

A regular expression (also called regex for short) is a fast way to work with strings of text. By formulating a regular expression with a special syntax, you can: search for text in a string.


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}$/);
like image 162
Chin Leung Avatar answered Oct 10 '22 22:10

Chin Leung