Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
191
rated 0 times [  197] [ 6]  / answers: 1 / hits: 59833  / 13 Years ago, wed, june 29, 2011, 12:00:00

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.


More From » regex

 Answers
26

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.


[#91438] Tuesday, June 28, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
victorw

Total Points: 484
Total Questions: 120
Total Answers: 107

Location: Faroe Islands
Member since Thu, Apr 8, 2021
3 Years ago
;