It is common knowledge that the exec method from RegExps can get used to find all matches in a string. However, I just found out that if the regexp matches the empty string this loop can get stuck forever
var s = '1234'
var r = /()/g;
var m;
var i = 0;
while( (m = r.exec(s)) ){
console.log(i, m[0]);
if(++i >= 50){ console.log("infinite loop!"); break }
}
What is really weird though is that the plain string.match methods does not get stuck:
'1234'.match(/()/g) // Gives ["", "", "", "", "", ""]
I wonder how the match method is defined to work differently from the exec loop. So far the only way I found to avoid getting stuck like the match method does involves abusing the string.replace method, in a horrid hack:
var matches = [];
'1234'.replace(/()/g, function(m){ matches.push(m) });
So my question is:
How do the match and replace return a finite results when the regexp matches the empty string? Can I use the same technique to avoid getting stuck in the exec loop?
One (icky) solution is to make sure it’s not in the same place as last time: