David
David

Reputation: 73604

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?

Upvotes: 3

Views: 387

Answers (3)

Tushar
Tushar

Reputation: 87233

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}$/;

Upvotes: 8

DRiFTy
DRiFTy

Reputation: 11369

You should use the regular expression literal (without quotes and using the beginning and ending slashes) when defining the RegExp object. This is the recommended approach when the regular expression will remain constant, meaning it does not need to be compiled every time it is used. This gives you the desired result:

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

Upvotes: 2

Ismael Fuentes
Ismael Fuentes

Reputation: 250

Because $ means End of line, and your string does not have an end of line as last character

May be you are looking for "\z"

Upvotes: -5

Related Questions