I have the following javascript code:
function checkLegalYear() { var val = "02/2010"; if (val != '') { var regEx = new RegExp("^(0[1-9]|1[0-2])/\d{4}$", "g"); if (regEx.test(val)) { //do something } else { //do something } } }
However, my regEx test always returns false for any value I pass (02/2010). Is there something wrong in my code? I've tried this code on various javascript editors online and it works fine.
You regex doesn't work, because you're matching the beginning of the line, followed by one or more word-characters (doesn't matter if you use the non-capturing group (?:…) here or not), followed by any characters.
If you use exec() or match() and if the match succeeds, these methods return an array and update properties of the associated regular expression object and also of the predefined regular expression object, RegExp . If the match fails, the exec() method returns null (which coerces to false ).
A regular expression can also be described as a sequence of pattern that defines a string. Regular expressions are used to match character combinations in strings. String searching algorithm used this pattern to find the operations on a string.
The string. match() is an inbuilt function in JavaScript used to search a string for a match against any regular expression. If the match is found, then this will return the match as an array. Parameters: Here the parameter is “regExp” (i.e. regular expression) which will compare with the given string.
Because you're creating your regular expression from a string, you have to double-up your backslashes:
var regEx = new RegExp("^(0[1-9]|1[0-2])/\\d{4}$", "g");
When you start with a string, you have to account for the fact that the regular expression will first be parsed as such — that is, as a JavaScript string constant. The syntax for string constants doesn't know anything about regular expressions, and it has its own uses for backslash characters. Thus by the time the parser is done with your regular expression strings, it will look a lot different than it does when you look at your source code. Your source string looks like
"^(0[1-9]|1[0-2])/\d{4}$"
but after the string parse it's
^(0[1-9]|1[0-2])/d{4}$
Note that \d
is now just d
.
By doubling the backslash characters, you're telling the string parser that you want single actual backslashes in the string value.
There's really no reason here not to use regular expression syntax instead:
var regEx = /^(0[1-9]|1[0-2])\/\d{4}$/g;
edit — I also notice that there's an embedded "/" character, which has to be quoted if you use regex syntax.
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