rac rac - 5 months ago 6
Javascript Question

Issue with Regular expression in IE

I have a problem in all versions of Internet Explorer with regular expressions. I get the error ”invalid syntax for regular expression”. It works fine in all other browsers including Microsoft Edge. While debugging in IE I noticed that it strips out ”/” in the beginning from the regex. Why does it do that?

var pattern = /^\d{10}$/;

function isPattern(input, pattern) {
if (typeof pattern === "string") {
pattern = "^" + pattern + "$";
}
var rePattern = new RegExp( pattern, "i" );
return (typeof input === "string" && rePattern.test( input ));
}


I suspect that the error is because in Explorer it removes the first "/" from regex.

Answer

Please remove "i" from var rePattern = new RegExp( pattern, "i" );

Actually, You should either pass a string to the constructor for regexen, or use the regex literal syntax, but not both.

var pattern = /^\d{10}$/i 

or

var pattern = new RegExp("^\d{10}$","i")

Refer here - http://stackoverflow.com/questions/16721057/ie8-is-not-recognizing-my-regular-expression