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
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.
The match() method retrieves the matches when matching a string against a regular expression. Use . test if you want a faster boolean check.
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.
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.
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$/;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With