Javascript RegEx Not Working


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.

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.


Your RegExp does work, but probably not as intended.

1. /.*v\=([\w-]+).*(&autoplay\=1)?/
2. /.*v\=([\w-]+).*(&autoplay\=1)/

  • The first RegExp has a quantifier ?, which means: "Match none or once".
  • This group is prefixed by .*, which means: "Match anything(except for newlines), as much as possible.
  • Because of the ? quantifier, the RegExp is also valid when &autoplay=1 isn't grouped (it will be matched by.*)

You're probably looking for this RegExp.

/.*v=([\w-]+).*?(&autoplay=1|$)/

  • .*? means: "Match anything(except for newlines), as less as possible to get the RegExp match.
  • (&autoplay=1|$) means: "Match &autoplay=1 or the end of the string ($). If end of the string identifier is omitted, .*? would match NOTHING, because .*? is also valid for an empty string.