Search code examples
javascriptregexdigit

Strange work RegExp in javascript


I want validate user input. User may input four digit only. I use RegExp for checking and see strange work. Javascript not understand \d

var expr1 = new RegExp("^\s*[0-9]{4,4}\s*");
var year = "1984";
alert (expr1.test(year));


var expr2 = new RegExp("^\s*\d{4,4}\s*");
alert (expr2.test(year));

It alerting "true" and "false". http://jsfiddle.net/HfHDu/

Why?


Solution

  • Always escape \ when using RegExp constructor

    var expr1 = new RegExp("^\\s*[0-9]{4,4}\\s*");
    var year = "1984";
    alert (expr1.test(year)); //true
    
    
    var expr2 = new RegExp("^\\s*\\d{4,4}\\s*");
    alert (expr2.test(year)); //true