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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With