I was experiencing some weird behaviour in some of my javascript code, but only in Firefox and Chrome. IE is fine.
I have isolated the problem and created a little page so you can see the behaviour yourself.
Essentially, it appears as if the Regular Expression object in MethodC is being reused across method calls to MethodC, even though it's a local variable. Can someone explain this behaviour?
<html>
<head>
<script type="text/javascript">
function RunDemo()
{
var subject = "01234 555 6789";
for (var i = 1; i <= 10; i++) {
MethodA(subject, i);
MethodB(subject, i);
MethodC(subject, i);
}
}
// OK, OK, OK, OK, OK, OK, OK, OK, OK, OK
function MethodA(subject, iteration)
{
var myRegexp = new RegExp("5", "g");
var matches = myRegexp.exec(subject);
AddItem(matches ? "OK" : "no match", "listA");
}
// OK, OK, OK, OK, OK, OK, OK, OK, OK, OK
function MethodB(subject, iteration)
{
var myRegexp = /5/;
var matches = myRegexp.exec(subject);
AddItem(matches ? "OK" : "no match", "listB");
}
// OK, OK, OK, no match, OK, OK, OK, no match, OK, OK (in FireFox and Chrome, IE is fine)
function MethodC(subject, iteration) {
var myRegexp = /5/g;
var matches = myRegexp.exec(subject);
AddItem(matches ? "OK" : "no match", "listC");
}
function AddItem(itemText, listID) {
var li = document.createElement("li");
li.innerHTML = itemText;
document.getElementById(listID).appendChild(li);
}
</script>
</head>
<body onload="RunDemo()">
<h2>Method A</h2>
<ul id="listA"></ul>
<h2>Method B</h2>
<ul id="listB"></ul>
<h2>Method C</h2>
<ul id="listC"></ul>
</body>
</html>