37

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.

0

1 Answer 1

102

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.

Sign up to request clarification or add additional context in comments.

12 Comments

The second solution is wrong, that / needs to be escaped. ...0-2])\/\d{4...
I went to fix it after I commented and saw you changed it. Just took quick.
"There's really no reason here not to use regular expression syntax instead" What if you want to concatenate your expressions? One from a library surrounded by other things?
var regex1 = RegExp('^([0-2][0-9]|(3)[0-1](\/)(((0)[0-9])|((1)[0-2]))(\/)d{4}$','g'); var str1 = '16/12/2018'; console.log(regex1.test(str1)); // expected output: true When I test in regex101, 16/12/2018, returns true, but when I use it in my javascript file, ity always return false, why?
@RahulSharma at the end of your regex, d{4} should be \d{4}. Also you probably don't need the "g" flag.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.