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

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

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


当前回答

jQueryGlobalize项目中还有Globalize.format,这是jQueryUI的官方全球化服务。当您需要具有文化意识的格式时,这很好。

其他回答

我使用模板文字方法,如下所示:

export const messages = {
  foo: (arg1, arg2) => `Hello ${arg1} ${arg2}`,
  bar: (arg1) => `Hello ${arg1}`,
}

从文件中:

console.log(messages.foo('Bar', 'World'))
console.log(messages.bar('Foo'))

jQueryGlobalize项目中还有Globalize.format,这是jQueryUI的官方全球化服务。当您需要具有文化意识的格式时,这很好。

此方法适用于{0}、{1}和{}。

String.prototype.format = function format()
{                                                                                                               
  var msg = this;
  for(var i in arguments)
    msg = msg.replace(/\{\}/,arguments[i]).replace(new RegExp('\\{'+i+'\\}','g'),arguments[i]);
  return msg;
}

我用这个:

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

    return newStr;
}

然后我称之为:

"<h1>%s</h1><p>%s</p>".format("Header", "Just a test!");

旧答案的修改代码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