JavaScript equivalent to printf/String.Format

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

    Building on the previously suggested solutions:

    // First, checks if it isn't implemented yet.
    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
          ;
        });
      };
    }
    

    "{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")

    outputs

    ASP is dead, but ASP.NET is alive! ASP {2}


    If you prefer not to modify String's prototype:

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

    Gives you the much more familiar:

    String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');

    with the same result:

    ASP is dead, but ASP.NET is alive! ASP {2}

提交回复
热议问题