I want to execute a regex in a loop and I get strange results. For
var a = [], r = /(.*)\.\$\.(.*)/g, s = 'text.$.text';
for (var i = 0; i < 10; i++) {
a.push(r.exec(s + i));
}
console.log(a);
I get
[Array[3], null, Array[3], null, Array[3], null, Array[3], null, Array[3], null]
For
var a = [], r = /t/g, s = 'text.$.text';
for (var i = 0; i < 10; i++) {
a.push(r.exec(s + i));
} console.log(a);
I get
[Array[1], Array[1], Array[1], Array[1], null, Array[1], Array[1], Array[1], Array[1], null]
It seems like a timing problem. My first thought was that //g.exec()
runs asynchronous and the complexer the regex is the more loop passes are to fast to execute the regex. But I can't find informations about this behaviour. What's happening here?