简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM