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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…