JavaScript的字符串格式化函数在IE浏览器中无法正常工作。

3

我在博客的评论中看到了这个JavaScript代码:frogsbrain

它是一个字符串格式化函数,在Firefox、Google Chrome、Opera和Safari中工作正常。唯一的问题是IE中该脚本没有任何替换。两个测试用例在IE中的输出仅为'hello',没有其它。

请帮我让这个脚本在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('')
}

我喜欢这个答案(https://dev59.com/pXNA5IYBdhLWcg3wPbSe#1038930),它更为简洁 :) - Mottie
2个回答

3
我认为问题出在这里。
var pattern = /({?){([^}]+)}(}?)/g;
var split = this.split(pattern);

Javascript的正则表达式split函数在IE浏览器和其他浏览器中表现不同。

请查看我在SO中的另一篇帖子


谢谢。那指引我朝着正确的方向前进。虽然您在评论中提供的链接没有解决这个问题,但我在这里找到了一个更通用的解决方案:http://blog.stevenlevithan.com/archives/cross-browser-split - Sebastian P.R. Gingter

1

var split = this.split(pattern);

string.split(regexp) 在IE(JScript)上存在许多问题,通常最好避免使用。 特别是:

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

    alert('abbc'.split(/(b)/)) // a,c

使用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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接