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?
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
尝试使用\\\\d
代替\\d
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.