Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegExp.test not working?

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

like image 581
user424134 Avatar asked Jul 22 '11 17:07

user424134


People also ask

What does RegExp test do?

JavaScript RegExp test() The test() method tests for a match in a string. If it finds a match, it returns true, otherwise it returns false.

Which is faster regex match or RegExp test?

The match() method retrieves the matches when matching a string against a regular expression. Use . test if you want a faster boolean check.

How do you check if a string matches a regex?

Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.

What does the regex 0 9 ]+ do?

In this case, [0-9]+ matches one or more digits. A regex may match a portion of the input (i.e., substring) or the entire input. In fact, it could match zero or more substrings of the input (with global modifier). This regex matches any numeric substring (of digits 0 to 9) of the input.


1 Answers

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$/;
like image 140
BoltClock Avatar answered Oct 19 '22 09:10

BoltClock