最佳答案
我真的为此疯狂了我已经花了不成比例的时间试图弄清楚这里发生了什么。所以请帮我一把
我需要在 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。我不明白为什么。
我张贴了一个小提琴 给你,在那里你可以运行和编辑的代码。
到目前为止,我已经在 Chrome 和 Firefox 中尝试过了。