Javascript:字符串的格式未定义

时间:2014-08-10 09:07:19

标签: javascript

我有以下javascript代码片段:

var someValue = 100;
var anotherValue = 555;
alert('someValue is {0} and anotherValue is {1}'.format(someValue, anotherValue));

收到以下错误:

Uncaught TypeError: undefined is not a function

我错过了什么,在这里?

2 个答案:

答案 0 :(得分:13)

String.format不是原生String扩展名。自己扩展它很容易:

String.prototype.format = function () {
        var args = [].slice.call(arguments);
        return this.replace(/(\{\d+\})/g, function (a){
            return args[+(a.substr(1,a.length-2))||0];
        });
};
// usage
'{0} world'.format('hello'); //=> 'hello world'

答案 1 :(得分:5)

String.format = function() {
            var s = arguments[0];
            for (var i = 0; i < arguments.length - 1; i += 1) {
                var reg = new RegExp('\\{' + i + '\\}', 'gm');
                s = s.replace(reg, arguments[i + 1]);
            }
            return s;
        };


var strTempleate = String.format('hello {0}', 'Ortal');