keldar
keldar

Reputation: 6242

Why does this RegExp exec cause an infinite loop?

I have the following block of code:

var field,
    reg = new RegExp('{{.*?}}', 'i'),
    text = 'This is a string with 1: {{param1}}, 2: {{param2}} and 3: {{param3}} parameters.';

while (field = reg.exec(text)) {
    console.log(field);
}

If I include a g global flag, the loop runs fine. But, if it's not global, surely reg.exec(text); should return null after just the first match and end the while loop?

Trying to understand the reason behind it, if somebody can elaborate I would greatly appreciate it.

Upvotes: 6

Views: 4267

Answers (2)

axelduch
axelduch

Reputation: 10849

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.

Upvotes: 6

Anthony Grist
Anthony Grist

Reputation: 38345

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.

Upvotes: 22

Related Questions