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

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

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


当前回答

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

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

其他回答

这很有趣,因为Stack Overflow实际上有自己的格式化函数,用于名为formatUnicorn的String原型。试试看!进入控制台并键入以下内容:

"Hello, {name}, are you feeling {adjective}?".formatUnicorn({name:"Gabriel", adjective: "OK"});

您将获得以下输出:

你好,加布里埃尔,你感觉还好吗?

您可以使用对象、数组和字符串作为参数!我得到了它的代码并对其进行了修改,以生成String.prototype.format的新版本:

String.prototype.formatUnicorn = String.prototype.formatUnicorn ||
function () {
    "use strict";
    var str = this.toString();
    if (arguments.length) {
        var t = typeof arguments[0];
        var key;
        var args = ("string" === t || "number" === t) ?
            Array.prototype.slice.call(arguments)
            : arguments[0];

        for (key in args) {
            str = str.replace(new RegExp("\\{" + key + "\\}", "gi"), args[key]);
        }
    }

    return str;
};

请注意,巧妙的Array.prototype.slice.call(arguments)调用——这意味着如果你输入的参数是字符串或数字,而不是一个JSON样式的对象,那么你几乎可以得到C#的String.Format行为。

"a{0}bcd{1}ef".formatUnicorn("FOO", "BAR"); // yields "aFOObcdBARef"

这是因为Array的切片会将参数中的任何内容强制到Array中,无论它最初是不是这样,并且关键字将是每个数组元素的索引(0,1,2…),该索引被强制到字符串中(例如,“0”,因此第一个正则表达式模式为“\\{0\\}”)。

整洁的

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

在typescript中,创建一个名为format.ts的文件,并导入您需要使用的任何格式。

// contents of format.ts

interface String {
  format(...args: any[]): string;
}

if (!String.prototype.format) {
  String.prototype.format = function() {
    let a = this;
    let b: any;
    // tslint:disable-next-line: forin
    for (b in arguments) {
      a = a.replace(/%[a-z]/, arguments[b]);
    }
    return a;
  };
}

要格式化字符串,请使用以下代码:

import './format';

console.log('Hello, %s!'.format('World'));

实例

String.prototype.format=函数(){设a=此;设b;for(参数中的b){a=a.replace(/%[a-z]/,自变量[b]);}返回a;};console.log(“您好,%s!”.format(“世界”));

有了sprintf.js,你可以制作一个漂亮的小格式

String.prototype.format = function(){
    var _args = arguments 
    Array.prototype.unshift.apply(_args,[this])
    return sprintf.apply(undefined,_args)
}   
// this gives you:
"{%1$s}{%2$s}".format("1", "0")
// {1}{0}

我在列表中没有看到pyformat,所以我想把它放进去:

console.log(pyformat( 'The {} {} jumped over the {}'
                , ['brown' ,'fox' ,'foobar']
                ))
console.log(pyformat('The {0} {1} jumped over the {1}'
                , ['brown' ,'fox' ,'foobar']
                ))
console.log(pyformat('The {color} {animal} jumped over the {thing}'
                , [] ,{color: 'brown' ,animal: 'fox' ,thing: 'foobaz'}
                ))