从这个来源在博客的评论工作,我有一个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('')
}
我喜欢这个答案(http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery/1038930#1038930),它更简洁:) – Mottie 2010-03-02 15:07:07