我正在寻找一个与C/PHP printf()或C#/Java程序员String.Format()(IFormatProvider for.NET)相当的JavaScript。

目前,我的基本要求是数字的千位分隔符格式,但处理大量组合(包括日期)的格式会很好。

我意识到Microsoft的Ajax库提供了String.Format()的一个版本,但我们不希望该框架的全部开销。


当前回答

对于基本格式:

var template = jQuery.validator.format("{0} is not a valid value");
var result = template("abc");

其他回答

这是https://stackoverflow.com/a/4673436/1258486对于CoffeeScript。

https://gist.github.com/eces/5669361

if String.prototype.format is undefined
  String.prototype.format = () ->
    _arguments = arguments
    this.replace /{(\d+)}/g, (match, number) ->
      if typeof _arguments[number] isnt 'undefined' then _arguments[number] else match

如果需要printf,请使用printf

看起来90%的评论从未使用过比%d更复杂的printf格式。例如,我想知道他们是如何输出货币价值的?

我开始将Java String.format(实际上是新的Formatter().format))移植到javascript。初始版本位于:

https://github.com/RobAu/javascript.string.format

您可以简单地添加javscript并调用StringFormat.format(“%.2f”,[2.4]);等

请注意,尚未完成,但欢迎反馈:)

虽然不是世界上最推荐的功能,但它确实有效。

如果需要sprintf,只需复制并粘贴相同的函数,并将return console.log(sb)更改为只返回sb。

printf=函数(s,/*args…*/){a=参数;al=a.length;如果(al<=1)返回-2;如果(al>=2&&s.toLowerCase().search(/%[a-z]/)==-1)返回-1;sb=s;对于(i=1;i<=al-1;i++){sb=某人替换(/%[a-z]/,a[i]);}返回控制台日志(sb);}var someString=“您好%s\n现在是%s:%s%s。\n今天是%s\n”;printf(someString,“StackOverflowUser”,“5”,“48”,“PM”,“漂亮”);

为了防止有人需要一个功能来防止污染全球范围,下面是一个功能:

  function _format (str, arr) {
    return str.replace(/{(\d+)}/g, function (match, number) {
      return typeof arr[number] != 'undefined' ? arr[number] : match;
    });
  };