Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this regular expression evaluate to false in javascript?

I'm looking for a string that is 0-9 digits, no other characters.

This is alerting me with a "false" value:

var regex = new RegExp('^[\d]{0,9}$');
alert(regex.test('123456789'));

These return true, and I understand why (The ^ and $ indicate that the whole string needs to match, not just a match within the string) :

var regex = new RegExp('[\d]{0,9}');
alert(regex.test('123456789'));

-

var regex = new RegExp('[\d]{0,9}');
alert(regex.test('12345678934341243124'));

and this returns true:

var regex = new RegExp('^[\d]{0,9}');
alert(regex.test('123456789'));

So why, when I add the "$" at the end would this possibly be failing?

And what do I need to do to fix it?

like image 790
David Avatar asked Dec 13 '25 02:12

David


1 Answers

When you use

var regex = new RegExp('^[\d]{0,9}$');

syntax, you'll get regex as

/^[d]{0,9}$/

Note the \d is turned into d.

This regex /^[d]{0,9}$/ will match only the d zero to nine times.

RegExp uses string to define regex, the \ is also used as escape symbol in the string, so \ in \d is considered as the escape character.

Escape the \ by preceding it with another \.

var regex = new RegExp('^[\\d]{0,9}$');

I'll recommend you to use regex literal syntax rather than the confusing RegExp syntax.

var regex = /^\d{0,9}$/;

EDIT:

The reason you get true when using var regex = new RegExp('^[\d]{0,9}'); is because the regex implies that the string should start with any number of d include zero to nine. So, event when the string does not starts with d the condition is stratified because of 0 as the minimum no of occurrences.

You might want to check if the string starts with one to nine digits.

var regex = /^\d{1,9}$/;
like image 81
Tushar Avatar answered Dec 14 '25 16:12

Tushar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!