When you use exec, the regex object "remembers" the index of the last match.
Allows you to record the value lastIndex:
reg = /A?/g;
reg.exec('AaAa');
console.log(reg.lastIndex);
reg.exec('AaAa');
console.log(reg.lastIndex);
reg.exec('AaAa');
console.log(reg.lastIndex);
As you can see, the index of the last match does not change! But why?
, (?).
exec , 1, "a", A?. , A? , .. "a". , , , , . .
-:
AaAa // does index 0 match "A?" ? Yes, consume "A" and increase index to 1
^
AaAa // does index 1 match "A?" ? Yes, but do not consume "a"
^
AaAa // does index 1 match "A?" ? Yes, but do not consume "a"
^
...
exec "a".
exec MDN.
, , .