Use of String.Format in JavaScript?

后端 未结 19 2027
逝去的感伤
逝去的感伤 2020-12-04 07:59

This is driving me nuts. I believe I asked this exact same question, but I can\'t find it any more (I used Stack Overflow search, Google Search, manually searched my po

19条回答
  •  情深已故
    2020-12-04 08:41

    if (!String.prototype.format) {
        String.prototype.format = function () {
            var args = arguments;
            return this.replace(/{(\d+)}/g, function (match, number) {
                return typeof args[number] != 'undefined'
                  ? args[number]
                  : match
                ;
            });
        };
    }
    

    Usage:

    '{0}-{1}'.format('a','b');
    // Result: 'a-b'
    

    JSFiddle

提交回复
热议问题