2010-01-28 35 views
3

从这个来源在博客的评论工作,我有一个JavaScript:frogsbrain的JavaScript功能的String.Format不会在IE

这是一个字符串格式,它在Firefox,谷歌Chrome,Opera和Safari浏览器工作正常。 唯一的问题是在IE中,脚本根本没有替换。 IE中两种测试用例的输出结果都只是'你好',没有其他的了。

请帮助我在IE中也可以使用这个脚本,因为我不是Javascript大师,我只是不知道从哪里开始寻找问题。

为了方便起见,我会在这里发布脚本。到目前为止,所有学分均为Terence Honles

// usage: 
// 'hello {0}'.format('world'); 
// ==> 'hello world' 
// 'hello {name}, the answer is {answer}.'.format({answer:'42', name:'world'}); 
// ==> 'hello world, the answer is 42.' 
String.prototype.format = function() { 
    var pattern = /({?){([^}]+)}(}?)/g; 
    var args = arguments; 

    if (args.length == 1) { 
     if (typeof args[0] == 'object' && args[0].constructor != String) { 
      args = args[0]; 
     } 
    } 

    var split = this.split(pattern); 
    var sub = new Array(); 

    var i = 0; 
    for (;i < split.length; i+=4) { 
     sub.push(split[i]); 
     if (split.length > i+3) { 
      if (split[i+1] == '{' && split[i+3] == '}') 
       sub.push(split[i+1], split[i+2], split[i+3]); 
      else { 
       sub.push(split[i+1], args[split[i+2]], split[i+3]); 
      } 
     } 
    } 

    return sub.join('') 
} 
+0

我喜欢这个答案(http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery/1038930#1038930),它更简洁:) – Mottie 2010-03-02 15:07:07

回答

3

我认为问题在于此。

var pattern = /({?){([^}]+)}(}?)/g; 
var split = this.split(pattern); 

Javascript的正则表达式拆分函数在IE中的行为与其他浏览器的行为不同。

请看看我的其他在post SO

+0

谢谢。这使我指出了正确的方向。 Allthough在你的帖子的评论中的链接并没有解决这个问题,我发现了一个更通用的解决方案:http://blog.stevenlevithan.com/archives/cross-browser-split – 2010-01-28 09:36:37

1

VAR分= this.split(图案);

string.split(regexp)以许多方式被打破上IE(JScript的),并且通常最好避免。特别是:

  • 它不包括在输出数组
  • 它省略空字符串

    警报中的匹配组('abbc'.split(/(B)/))//一个, ç

这似乎更容易使用replace而非split

String.prototype.format= function(replacements) { 
    return this.replace(String.prototype.format.pattern, function(all, name) { 
     return name in replacements? replacements[name] : all; 
    }); 
} 
String.prototype.format.pattern= /{?{([^{}]+)}}?/g;