Ccna final exam - java, php, javascript, ios, cshap all in one. This is a collaboratively edited question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
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.
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++;
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.
ReplyDeletevar count=0, rx=/\s+/g, rx.lastIndex=100;
while(rx.test(string))count++;