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

Why Is My JavaScript Regular Expression Not Working

Mary-Kate Olsen
Release: 2024-10-18 13:25:30
Original
499 people have browsed it

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");
Copy after login

Correct Code:

var regEx = new RegExp("^(0[1-9]|1[0-2])//\d{4}$", "g");
Copy after login

Or, even simpler, use regular expression syntax without needing to escape the slashes:

var regEx = /^(0[1-9]|1[0-2])/\d{4}$/g;
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template