Home  >  Article  >  Web Front-end  >  Why Is My JavaScript Regular Expression Not Working

Why Is My JavaScript Regular Expression Not Working

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-18 13:25:30472browse

Why Is My JavaScript Regular Expression Not Working

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn