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

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

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


当前回答

这是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

其他回答

如果您希望处理千位分隔符,那么应该真正使用JavaScript Number类中的toLocaleString(),因为它将为用户所在区域设置字符串格式。

JavaScript Date类可以格式化本地化的日期和时间。

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

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

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

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

JavaScript有“sprintf”,您可以在http://www.webtoolkit.info/javascript-sprintf.html.

我很惊讶没有人使用reduce,这是一个本机简洁而强大的JavaScript函数。

ES6(EcmaScript2015)

String.prototype.format=函数(){return[…arguments].reduce((p,c)=>p.replace(/%s/,c),this);};console.log('是%s还是%s?…不,是%s!'。格式('平面','鸟','SOman');

<ES6

function interpolate(theString, argumentArray) {
    var regex = /%s/;
    var _r=function(p,c){return p.replace(regex,c);}
    return argumentArray.reduce(_r, theString);
}

interpolate("%s, %s and %s", ["Me", "myself", "I"]); // "Me, myself and I"

工作原理:

reduce对累加器和数组中的每个元素(从左到右)应用一个函数,以将其减少为单个值。

var _r=函数(p,c){return p.replace(/%s/,c)};控制台日志([“a”,“b”,“c”].reduce(_r,“[%s],[%s]和[%s]”)+'\n',[1,2,3].reduce(_r,“%s+%s=%s”)+'\n',[“cool”,1337,“stuff”].reduce(_r,“%s%s%s”));

旧答案的修改代码https://stackoverflow.com/a/18234317/19531844效率更高(没有较慢的RegExp)且更短

String.prototype.formatUnicorn = function () {
    let str = this.toString();
    if(!arguments.length) {
        return;
    };
    const [args] = arguments;
    for (const key of Object.keys(args)) {
        str = str.replaceAll(`{${key}}`, args[key]);
    };
    return str;
};

用法:

"{test} {test_2} {test}".formatUnicorn({"test": "hello", "test_2": "world"}); // yields hello world hello

新旧基准:https://jsben.ch/BRovx