Why does this RegExp exec cause an infinite loop?

The MDN documentation for RegExp.prototype.exec() has what I think is the answer when explaining the value of the lastIndex property of the RegExp object:

The index at which to start the next match. When “g” is absent, this will remain as 0.

So each time you call .exec() on that RegExp object, it will start from the beginning of the string again. If there’s at least one match, that means it will always find a match, and your loop will never end.

Its because RegExp.prototype.exec combined with g flag actually mutates the start index of the RegExp instance itself.

On the other hand without g flag, it does not mutate, therefore it returns always the first result, if it matches your while loop will go gorilla.

Read more here: Source link