Search code examples
javascriptregexwebdigits

JS regexp to find only 1 or 2 long digits


Here's my code:

var dayRegX      = new RegExp("\\b" + "\\d{1, 2}" + "\\b", "g");
if(!dayRegX.test(day.value)){
    alert('not good');
}

The test method returns false all the time, so I get the alert, why is that? It supposed to return true, if I type in a 1 or 2 long digit. Thanks


Solution

  • Be careful with spaces in regex, there shouldn't be a space between 1, and 2, plus it doesn't seem like you need the RegExp constructor there:

    var regex = /\b\d{1,2}\b/g;
    if ( !regex.test(day.value) ) { ... }