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?
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.
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.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
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.
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}$/);
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