问题描述
我有以下代码块:
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 $ c $的值时,我认为是答案c> 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导致无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!