Javascript正则表达式跨浏览器差异

时间:2012-08-24 12:54:09

标签: javascript regex internet-explorer firefox cross-browser

这段代码带来了Firefox到IE8的不同结果:

var text = "[AMOUNT] MILES DEDUCTED IN [CABIN] FOR [ORIGIN]";
var splitArray = text.split(/[\[\]]/);
alert(splitArray.length);   

在Firefox中,警报提供7。 在IE中,它给出了5。

我试过......

Javascript RegEx trouble in Internet Explorer

但它不起作用。

请问好吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

下一个代码没有经过全面测试,但在快速测试中它运行正常:

获得IE8并减少分裂行为:

var text = "[AMOUNT] MILES DEDUCTED IN [CABIN] FOR [ORIGIN]";
var arr = text.match(/[^\[\]]+/g);
// arr is ["AMOUNT", " MILES DEDUCTED IN ", "CABIN", " FOR ", "ORIGIN"]

获得FF分裂行为:

var text = "[AMOUNT] MILES DEDUCTED IN [CABIN] FOR [ORIGIN]";
var arr = text.match(/[^\[\]]+|^(?=[\[\]])|[^\[\]]?(?=[\[\]]$)|[^\[\]]?(?=[\[\]]{2})/g);
// arr is ["", "AMOUNT", " MILES DEDUCTED IN ", "CABIN", " FOR ", "ORIGIN", ""]