Reputation: 2093
I am trying to validate a variable contains a 9-digit number in Javascript. This should be basic but for some reason this is failing:
var test = "123123123";
var pattern = new RegExp("/\d{9}/");
if(test.match(pattern))
{
//This code never executes
}
else
{
//This code is always executing
alert('no match!');
}
Can anyone see why I am not getting a match?
I also tried type-casting test to an integer with:
test = Number(test);
...but this doesn't work as it has to be a String to support the .match method.
Upvotes: 11
Views: 80253
Reputation: 270607
When using a new Regexp()
constructor, you should not include the /
delimieters, since they are treated as literals in the expression.
Also your expression should be anchored ^$
to ensure it contains no other characters than the nine digits.
var test = "123123123";
// \d would need to be escaped as \\d in RegExp()
var pattern = new RegExp("^\\d{9}$");
// ..Or...
var pattern = new RegExp("^[0-9]{9}$");
Using a regular expression literal without new Regexp()
is often a better strategy if you don't need to do string manipulations or include variables in the regex, since it avoids the extra backslash-escaping.
var pattern = /^\d{9}$/;
Upvotes: 5
Reputation: 2067
Try removing the slashes and escaping the backslash:
var test = "123123123";
var pattern = new RegExp("\\d{9}");
if(test.match(pattern))
{
//This code never executes
alert("match");
}
else
{
//This code is always executing
alert('no match!');
}
Upvotes: 1
Reputation: 359786
You're mixing the two different regex constructors. Pick one:
var pattern = new RegExp("^\\d{9}$");
// or
var pattern = /^\d{9}$/;
N.B. you probably want to add start and end anchors (as above) to make sure the whole string matches.
Upvotes: 27
Reputation: 369448
You aren't looking for 9 consecutive digits, you are looking for 9 consecutive digits enclosed in slashes.
Upvotes: 2
Reputation: 141628
You are mixing regex literal syntax with the RegExp class. Try:
var test = "123123123";
var pattern = /\d{9}/;
if(test.match(pattern))
{
alert('match!');
//This code never executes
}
else
{
//This code is always executing
alert('no match!');
}
Additionally, you may want to change your regex to match on the beginning and end of line if you want to ensure it contains only a 9 digit number. Right now the regex will match any string that contains a 9 digit number. You would change it like so:
var pattern = /^\d{9}$/;
Upvotes: 11