JavaScript equivalent to printf/String.Format

前端 未结 30 2567
囚心锁ツ
囚心锁ツ 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 05:25

    I use this one:

    String.prototype.format = function() {
        var newStr = this, i = 0;
        while (/%s/.test(newStr))
            newStr = newStr.replace("%s", arguments[i++])
    
        return newStr;
    }
    

    Then I call it:

    "

    %s

    %s

    ".format("Header", "Just a test!");

提交回复
热议问题