0

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

Community
  • 1
  • 1
painotpi
  • 6,894
  • 1
  • 37
  • 70

1 Answers1

5

To quote MDN:

As with exec (or in combination with it), test called multiple times on the same global regular expression instance will advance past the previous match.

Currently what is happening is:

  1. the regular expression stored in patt tests the second string, finds a match at the index 1, and retains this information
  2. The next time you use test it tries to find a match from index 1 onwards, which obviously yields no match, since it is effectively testing the string "our"
  3. This resets the pointer to 0, allowing the match in the next string at index 1 to be found.

So to solve your problem, simply create a new instance on each iteration:

for (var i = 0; i < arr.length; i++)
{
    if (/h/gi.test(arr[i])) {
        test.innerHTML += " " + arr[i];
    }
}

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/

Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139