开发者

RegExp.test not working?

开发者 https://www.devze.com 2023-03-22 02:41 出处:网络
I am trying to validate year using Regex开发者_如何学Python.test in javascript, but no able to figure out why its returning false.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消