JavaScript String format

http://stackoverflow.com/questions/1038746/equivalent-of-string-format-in-jquery

This is a faster/simpler (and prototypical) variation of the function that Josh posted:

String.prototype.format = String.prototype.f = function() {
    var s = this,
        i = arguments.length;

    while (i--) {
        s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return s;
};

Usage:

'Added {0} by {1} to your collection'.f(title, artist)
'Your balance is {0} USD'.f(77.7) 

I use this so much that I aliased it to just f, but you can also use the more verbose format. e.g. 'Hello {0}!'.format(name)

发布了386 篇原创文章 · 获赞 19 · 访问量 82万+

猜你喜欢

转载自blog.csdn.net/watson243671/article/details/23187815
今日推荐