Thursday, May 10, 2012

Why does the "g” modifier give different results when test() is called twice?


Given this code:




var reg = /a/g;
console.log(reg.test("a"));
console.log(reg.test("a"));



I get this result:




true
false



I have no idea how this could happen. I have tested in both Node.js (v8) and Firefox browser.


Source: Tips4all

1 comment:

  1. Usually a test is chosen to check if some pattern matches at all, but the global flag lets you loop through a string to either count the matches or,like exec, do something with each lastIndex. Another use is to set the lastIndex of the rx yourself before the test is peformed, to ignore matches before some character index.

    var count=0, rx=/\s+/g, rx.lastIndex=100;
    while(rx.test(string))count++;

    ReplyDelete