JavaScript RegEx Not Working?
Your code checks the legality of a date format using a regular expression, but it always returns false. The issue lies in the construction of the regular expression.
As you're initializing the regular expression from a string, you need to double-quote the backslashes () in the pattern. This is because the string parser treats backslashes as special characters for string constants.
Incorrect Code:
var regEx = new RegExp("^(0[1-9]|1[0-2])/\d{4}$", "g");
Correct Code:
var regEx = new RegExp("^(0[1-9]|1[0-2])//\d{4}$", "g");
Or, even simpler, use regular expression syntax without needing to escape the slashes:
var regEx = /^(0[1-9]|1[0-2])/\d{4}$/g;
Now, the regular expression should correctly match the dates with the format "MM/YYYY". Make sure to double-quote any slashes (/) embedded within the regular expression pattern.
The above is the detailed content of Why Is My JavaScript Regular Expression Not Working. For more information, please follow other related articles on the PHP Chinese website!