Possible Duplicate:
Why RegExp with global flag in Javascript give wrong results?
My code is as follows,
HTML:
<p id="test"></p>
JavaScript:
var patt = /h/gi;
var arr = ["", "2Hour", "4Hour", "8Hour", "Next Business Day"];
var test = document.getElementById("test");
for (var i = 0; i < arr.length; i++)
{
if (patt.test(arr[i])) {
test.innerHTML += " " + arr[i];
}
}
However, the output that get is 2Hour 8Hour, why’s 4Hour not a part of the output?
Is there something wrong with my regex? how can I solve this issue?
I’ve put it up on fiddle
To quote MDN:
Currently what is happening is:
patttests the second string, finds a match at the index1, and retains this informationtestit tries to find a match from index1onwards, which obviously yields no match, since it is effectively testing the string
"our"0, allowing the match in the nextstring at index
1to be found.So to solve your problem, simply create a new instance on each iteration:
This “clears the pointer” as it were, and ensures that the regex behaves identically for each string it is tested against.
Here is a demonstration: http://jsfiddle.net/QbXEX/12/