我真的为此发疯了,我已经花了不成比例的时间来试图弄清楚这里发生了什么。所以请帮我一把 =)
我需要在 JavaScript 中对字符串进行一些 RegExp 匹配。不幸的是,它的行为非常奇怪。这段代码:
var rx = /(cat|dog)/gi;
var w = new Array("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) {
var m = null;
m = rx.exec(w[i]);
if(m){
document.writeln("<pre>" + i + "\nINPUT: " + w[i] + "\nMATCHES: " + m.slice(1) + "</pre>");
}else{
document.writeln("<pre>" + i + "\n'" + w[i] + "' FAILED.</pre>");
}
}
为前两个元素返回“cat”和“dog”,这是应该的,但随后一些 -exec()
调用开始返回null
。我不明白为什么。
我在这里发布了一个 Fiddle ,您可以在其中运行和编辑代码。
到目前为止,我已经在 Chrome 和 Firefox 中尝试过这个。