17

I am trying to validate year using Regex.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

1
  • Uh, do you mean "1981, 2007" or "1981" and "2007"? Commented Jul 22, 2011 at 17:28

4 Answers 4

40

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$/;
Sign up to request clarification or add additional context in comments.

2 Comments

you save me! man. god, bless you. what is the reason of /[0-9]*/.test("L") return true? in ionic or javascript or ...
@Mote Zart: The single backslash means nothing in a string if it isn't escaped so you're just testing for the literal string w+. That's why it needs to be doubled.
12

Found the REAL issue:

Change your declaration to remove quotes:

var regEx = new RegExp(/^(19|20)[\d]{2,2}$/); 

3 Comments

You may as well just use the regex literal rather than passing it to another RegExp constructor.
True. Although it was interesting to figure out the issue with the original ask.
(head banging)This is the correct answer- the single quotes encapsulating the reg expression. I have up-voted all involved as all helpful.
3

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.

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.