【问题标题】:IE8 parses this simple regex differently from all other browsersIE8 解析这个简单的正则表达式与所有其他浏览器不同
【发布时间】:2012-06-22 06:33:48
【问题描述】:

我正在尝试使用此函数从value

创建 2 个结果
function split(val){
  return val.split( /,\s*/ );
};
value = "Jim, ";
var terms = split( value );

terms;

所有其他浏览器,包括 IE9,都会产生terms = ["Jim", ""]

但是,IE8 和可能的 IE7 会产生这个:terms = ["Jim"]

有没有人有任何可能适用于 IE8 的建议或替代方案?

【问题讨论】:

  • 有趣的发现。 IE8 在用字符串拆分时表现正常(例如本例中的", "),但在用正则表达式拆分时末尾没有那个空字符串......奇怪。
  • 对于替代方案,请参阅 [stackoverflow.com/questions/1453521/… [1] 上的答案:stackoverflow.com/questions/1453521/…
  • 你能解释一下在什么情况下你会担心数组上的最后一个元素是空的吗?看看我的编辑

标签: javascript regex internet-explorer-8


【解决方案1】:

你可能会更好:

val.split(',')

这似乎在所有浏览器中都能正常工作。

逗号之后的任何尾随空格仍然必须在之后被剥离。大致如下:

for (var i = 0; i < terms.length; i++) {
    terms[i] = terms[i].replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

显然,在 IE8 和更早版本中,当使用正则表达式参数时,split() 会忽略空字符串匹配。字符串参数可以正常工作:

'axx'.split('x')    // All browsers: ["a", "", ""]
'axx'.split(/x/)    // IE6/7/8: ["a"], all other browsers: ["a", "", ""]

【讨论】:

    【解决方案2】:

    你将不得不重写正则表达式。

    试试这个。

    String.prototype.trim = String.prototype.trim || function() {
        return this.replace(/^\s+|\s+$/g, ''); 
    }
    function split( str ){
        return (""+str).trim().split( /\,/ );
    }
    

    【讨论】:

      猜你喜欢
      • 2011-04-11
      • 2021-08-27
      • 2013-05-18
      • 1970-01-01
      • 2011-10-28
      • 2020-01-30
      • 2012-08-10
      • 2015-05-05
      • 1970-01-01
      相关资源
      最近更新 更多