JavaScript equivalent to printf/String.Format

前端 未结 30 2423
囚心锁ツ
囚心锁ツ 2020-11-21 04:27

I\'m looking for a good JavaScript equivalent of the C/PHP printf() or for C#/Java programmers, String.Format() (IFormatProvider for .

30条回答
  •  傲寒
    傲寒 (楼主)
    2020-11-21 05:16

    Very elegant:

    String.prototype.format = function (){
        var args = arguments;
        return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (curlyBrack, index) {
            return ((curlyBrack == "{{") ? "{" : ((curlyBrack == "}}") ? "}" : args[index]));
        });
    };
    
    // Usage:
    "{0}{1}".format("{1}", "{0}")
    

    Credit goes to (broken link) https://gist.github.com/0i0/1519811

提交回复
热议问题