Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex - 9-digit number

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.

like image 624
Dan Avatar asked Aug 16 '12 13:08

Dan


People also ask

What does the regex 0 9 ]+ do?

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.

What is the regex represent 0 9?

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.

What is *$ in regex?

. * therefore means an arbitrary string of arbitrary length. ^ indicates the beginning of the string. $ indicates the end of the string.

Can regex be used for numbers?

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.


1 Answers

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.

like image 139
Matt Ball Avatar answered Sep 23 '22 17:09

Matt Ball