July 29th, 2009, 11:51 AM
Regex exec() not working in IE8
Any ideas on how to work around to use exec() with IE8?
Here is the sample code to show the issue:
var str = "images/1t.png";
var withMatch = str.match(re1);
var withExec = re1.exec(str);
document.write("withMatch=" + withMatch+"<br />");
document.write("withExec=" + withExec);
IE8: withMatch=images/ withExec=null
Firefox and Chrome withMatch=images/ withExec=images/
July 29th, 2009, 12:09 PM
Why do you want to use exec()? It is extremely heavy on computation and can be dangerous.
July 29th, 2009, 04:17 PM
Say what? RegExp.exec() is actually less computationally intensive than String.match(), since the latter will find all matches on a global search. Also, I'm not sure how running a match for a regular expression could be dangerous. Are you thinking of eval() perhaps?
Originally Posted by Winters
Anyway, I can confirm this behavior in IE8.
The problem seems to be that when running String.match() with a global RegExp (the g after the last /) it sets the RegExp's lastIndex property. This means that when you then call exec() on that RegExp, it is looking for the next match, but there isn't one. Thus, null.
There are a couple of workarounds:
- Don't call String.match() with the RegExp before calling exec()
- Set the RegExp's lastIndex back to 0 after calling String.match()
- Don't use a global match RegExp (it will only return the first match, which RegExp.exec() does anyway until you call it again)
Firefox and Safari seem to leave lastIndex alone after String.match(), and I didn't test any other versions of IE.
Comments on this post
Last edited by jnsg; July 29th, 2009 at 04:20 PM.
July 29th, 2009, 05:08 PM
Originally Posted by jnsg
Thanks so much, setting lastIndex to 0 after the match() fixes it!