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

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

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


当前回答

除了zippoxer的答案,我还使用了这个函数:

String.prototype.format = function () {
    var a = this, b;
    for (b in arguments) {
        a = a.replace(/%[a-z]/, arguments[b]);
    }
    return a; // Make chainable
};

var s = 'Hello %s The magic number is %d.';
s.format('world!', 12); // Hello World! The magic number is 12.

我还有一个非原型版本,我经常使用它的类似Java的语法:

function format() {
    var a, b, c;
    a = arguments[0];
    b = [];
    for(c = 1; c < arguments.length; c++){
        b.push(arguments[c]);
    }
    for (c in b) {
        a = a.replace(/%[a-z]/, b[c]);
    }
    return a;
}
format('%d ducks, 55 %s', 12, 'cats'); // 12 ducks, 55 cats

ES 2015更新

ES 2015中所有酷炫的新功能让这一切变得更加简单:

function format(fmt, ...args){
    return fmt
        .split("%%")
        .reduce((aggregate, chunk, i) =>
            aggregate + chunk + (args[i] || ""), "");
}

format("Hello %%! I ate %% apples today.", "World", 44);
// "Hello World, I ate 44 apples today."

我想,因为这和以前的一样,实际上并不能解析字母,所以最好只使用一个标记%%。这样做的好处是显而易见的,并且不会使使用单一的%变得困难。但是,如果出于某种原因需要%%,则需要将其替换为自身:

format("I love percentage signs! %%", "%%");
// "I love percentage signs! %%"

其他回答

下面是一个非常简短的函数,它执行printf的一个子集,并在开发人员控制台中显示结果:

function L(...values)
    {
    // Replace each '@', starting with the text in the first arg
    console.log(values.reduce(function(str,arg) {return str.replace(/@/,arg)}));
    } // L

这里有一个测试:

let a=[1,2,3];
L('a: [@]',a);

输出类似于:a=[1,2,3]

PHPJS项目为许多PHP函数编写了JavaScript实现。由于PHP的sprintf()函数与C的printf()函数基本相同,所以它们的JavaScript实现应该可以满足您的需求。

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

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

从文件中:

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

String.prototype.format=函数(){var final=字符串(this);for(设i=0;i<arguments.length;i++){final=final.replace(“%s${i+1}”,参数[i])}return final |“”}console.log((“hello%s2 how%s3 you%s1”).format('hi','hello','how'));<h1 id=“text”></h1>

对于Node.js用户,util.format具有类似printf的功能:

util.format("%s world", "Hello")