JavaScript equivalent to printf/String.Format

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

    One very slightly different version, the one I prefer (this one uses {xxx} tokens rather than {0} numbered arguments, this is much more self-documenting and suits localization much better):

    String.prototype.format = function(tokens) {
      var formatted = this;
      for (var token in tokens)
        if (tokens.hasOwnProperty(token))
          formatted = formatted.replace(RegExp("{" + token + "}", "g"), tokens[token]);
      return formatted;
    };
    

    A variation would be:

      var formatted = l(this);
    

    that calls an l() localization function first.

提交回复
热议问题