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.
In this case, [0-9]+ matches one or more digits. A regex may match a portion of the input (i.e., substring) or the entire input. In fact, it could match zero or more substrings of the input (with global modifier). This regex matches any numeric substring (of digits 0 to 9) of the input.
The [^0-9] expression is used to find any character that is NOT a digit. The digits inside the brackets can be any numbers or span of numbers from 0 to 9. Tip: Use the [0-9] expression to find any character between the brackets that is a digit.
. * therefore means an arbitrary string of arbitrary length. ^ indicates the beginning of the string. $ indicates the end of the string.
The regex [0-9] matches single-digit numbers 0 to 9. [1-9][0-9] matches double-digit numbers 10 to 99. That's the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.
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.
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