RegExp.test not working?
I am trying to validate year using Regex开发者_如何学Python.test in javascript, but no able to figure out why its returning false.
var regEx = new RegExp("^(19|20)[\d]{2,2}$");
regEx.test(inputValue)
returns false for input value 1981, 2007
Thanks
As you're creating a RegExp
object using a string expression, you need to double the backslashes so they escape properly. Also [\d]{2,2}
can be simplified to \d\d
:
var regEx = new RegExp("^(19|20)\\d\\d$");
Or better yet use a regex literal to avoid doubling backslashes:
var regEx = /^(19|20)\d\d$/;
Found the REAL issue:
Change your declaration to remove quotes:
var regEx = new RegExp(/^(19|20)[\d]{2,2}$/);
Do you mean
var inputValue = "1981, 2007";
If so, this will fail because the pattern is not matched due to the start string (^) and end string ($) characters.
If you want to capture both years, remove these characters from your pattern and do a global match (with /g)
var regEx = new RegExp(/(?:19|20)\d{2}/g);
var inputValue = "1981, 2007";
var matches = inputValue.match(regEx);
matches will be an array containing all matches.
I've noticed, for reasons I can't explain, sometimes you have to have two \\ in front of the d.
so try [\\d] and see if that helps.
精彩评论