JavaScript equivalent to printf/String.Format

前端 未结 30 2407
囚心锁ツ
囚心锁ツ 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:08

    +1 Zippo with the exception that the function body needs to be as below or otherwise it appends the current string on every iteration:

    String.prototype.format = function() {
        var formatted = this;
        for (var arg in arguments) {
            formatted = formatted.replace("{" + arg + "}", arguments[arg]);
        }
        return formatted;
    };
    

提交回复
热议问题