exec导致无限循环

exec导致无限循环

本文介绍了为什么这个RegExp exec导致无限循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码块:

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);
}

如果我包含 g 全局标志,循环运行正常。但是,如果它不是全局的,肯定 reg.exec(文本); 应该在第一场比赛后返回 null 结束循环?

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.

推荐答案

在解释 lastIndex RegExp对象的属性:

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:

所以每次拨打<$在该RegExp对象上的c $ c> .exec(),它将再次从字符串的开头开始。如果至少有一个匹配,这意味着它总是会找到一个匹配,并且你的循环永远不会结束。

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.

这篇关于为什么这个RegExp exec导致无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 07:38