Using the g(global) flag with .exec stores the index up to which the pattern matches. If the pattern does not match, the index is reset to 0.
If the previous search was successful, the next search starts after the stored index, even though the string is different. This is because the regular expression stores the matched index. I encountered this bug while writing an input validator. Took me half a day to figure this out. 😅😅
Using the
g
(global) flag with.exec
stores the index up to which the pattern matches. If the pattern does not match, the index is reset to 0.If the previous search was successful, the next search starts after the stored index, even though the string is different. This is because the regular expression stores the matched index. I encountered this bug while writing an input validator. Took me half a day to figure this out. 😅😅
Here is the explanation from the docs
So for the above code:
Thus the output is:
Great breakdown, thanks for taking the time to explain it in such detail!!