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

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

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


当前回答

我用这个:

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!");

其他回答

+1 Zippo,但函数体需要如下所示,否则它会在每次迭代时附加当前字符串:

String.prototype.format = function() {
    var formatted = this;
    for (var arg in arguments) {
        formatted = formatted.replace("{" + arg + "}", arguments[arg]);
    }
    return formatted;
};

我将添加我自己的发现,这些发现是我问过之后发现的:

number_format(用于千位分隔符/货币格式)sprintf(作者同上)

遗憾的是,sprintf似乎不能像.NET的字符串格式那样处理千位分隔符格式。

这不是sprintf的精确复制;然而,它是类似的,并且更强大:https://github.com/anywhichway/stringformatter

使用此库的格式表达式采用嵌入式Javascript对象的形式,例如。

format("I have {number: {currency: "$", precision:2}}.",50.2); 

将返回“我有50.20美元”。

bobjs可以做到这一点:

var sFormat = "My name is {0} and I am {1} years old."; 
var result = bob.string.formatString(sFormat, "Bob", 29); 
console.log(result); 
//output: 
//========== 
// My name is Bob and I am 29 years old. 
export function stringFormat (str: string, ...args: string[]) {
     return args.reduce((acc, curr, i) => acc.replace(new RegExp("\\{" + i + "\\}", 'g'), curr), str);
}