Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 589
keldar Avatar asked Aug 12 '15 15:08

keldar


2 Answers

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.

like image 60
Anthony Grist Avatar answered Nov 04 '22 22:11

Anthony Grist


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.

like image 40
axelduch Avatar answered Nov 04 '22 22:11

axelduch