I am seriously going crazy over this and I\'ve already spent an unproportionate amount of time on trying to figure out what\'s going on here. So please give me a hand =)
Two things:
g
(global) flag. To solve this I recommed simply assign 0
to the lastIndex
member of the RegExp
object. This have better performance than destroy-and-recreate.in
keyword in order to walk an Array
object, because can lead to unexpected results with some libs. Sometimes you should check with somethign like isNaN(i)
, or if you know it don't have holes, use the classic for loop.The code can be:
var rx = /(cat|dog)/gi;
w = ["I have a cat and a dog too.", "There once was a dog and a cat.", "I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat.","I have a cat and a dog too.", "There once was a dog and a cat."];
for (var i in w)
if(!isNaN(i)) // Optional, check it is an element if Array could have some odd members.
{
var m = null;
m = rx.exec(w[i]); // Run
rx.lastIndex = 0; // Reset
if(m)
{
document.writeln("" + i + "\nINPUT: " + w[i] + "\nMATCHES: " + m.slice(1) + "
");
} else {
document.writeln("" + i + "\n'" + w[i] + "' FAILED.
");
}
}