I recently had a question that was answered, but I'm still trying to grasp why the regex behaves in a certain way.
According to w3schools, it explains:
g: Perform a global match (find all matches rather than stopping after the first match)
Okay, I understand. That's why the code returns an array like in this example:
var str="The rain in SPAIN stays mainly in the plain";
var patt1=/ain/gi;
document.write(str.match(patt1));
Output:
ain,AIN,ain,ain
The use of /g
in the regex is to replace more than one instance.
However, when looking at the test method:
var re=/hi/gi;
alert(re.test("hi") + " " + re.test("hi"));
The result comes out as "true false".
This inconsistency is puzzling. Why does the behavior change for each call? Shouldn't the global flag work consistently across all calls?
It seems that the lastIndex
property is being shared between calls, causing unexpected results. This shared state is not explicitly mentioned and caught me off guard. When would I actually need or want this 'feature'?