why does my javascript regex.test() give alternating results

JavascriptRegex

Javascript Problem Overview


> Possible Duplicate:
> Javascript regex returning true.. then false.. then true.. etc

var r = /\d/g;
var a = r.test("1"); // will be true
var b = r.test("1"); // will be false
console.log(a == b); // will be false

Please explain to me why the result of r.test("1") alternates with each call?

I was able to work around the issue I was having by removing the g modifier. However I would still like to understand why this happens.

Javascript Solutions


Solution 1 - Javascript

When you're using /g, the regex object will save state between calls (since you should be using it to match over multiple calls). It matches once, but subsequent calls start from after the original match.

(This is a duplicate of https://stackoverflow.com/questions/2630418/)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDennis GeorgeView Question on Stackoverflow
Solution 1 - JavascriptpkhView Answer on Stackoverflow