我正在寻找一个与C/PHP printf()或C#/Java程序员String.Format()(IFormatProvider for.NET)相当的JavaScript。
目前,我的基本要求是数字的千位分隔符格式,但处理大量组合(包括日期)的格式会很好。
我意识到Microsoft的Ajax库提供了String.Format()的一个版本,但我们不希望该框架的全部开销。
我正在寻找一个与C/PHP printf()或C#/Java程序员String.Format()(IFormatProvider for.NET)相当的JavaScript。
目前,我的基本要求是数字的千位分隔符格式,但处理大量组合(包括日期)的格式会很好。
我意识到Microsoft的Ajax库提供了String.Format()的一个版本,但我们不希望该框架的全部开销。
当前回答
我使用模板文字方法,如下所示:
export const messages = {
foo: (arg1, arg2) => `Hello ${arg1} ${arg2}`,
bar: (arg1) => `Hello ${arg1}`,
}
从文件中:
console.log(messages.foo('Bar', 'World'))
console.log(messages.bar('Foo'))
其他回答
下面是一个非常简短的函数,它执行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]
如果需要printf,请使用printf
看起来90%的评论从未使用过比%d更复杂的printf格式。例如,我想知道他们是如何输出货币价值的?
这里是sprintf在JavaScript中的一个最小实现:它只执行“%s”和“%d”,但我为它保留了扩展空间。这对OP来说是无用的,但其他偶然发现这条来自谷歌的线索的人可能会从中受益。
function sprintf() {
var args = arguments,
string = args[0],
i = 1;
return string.replace(/%((%)|s|d)/g, function (m) {
// m is the matched format, e.g. %s, %d
var val = null;
if (m[2]) {
val = m[2];
} else {
val = args[i];
// A switch statement so that the formatter can be extended. Default is %s
switch (m) {
case '%d':
val = parseFloat(val);
if (isNaN(val)) {
val = 0;
}
break;
}
i++;
}
return val;
});
}
例子:
alert(sprintf('Latitude: %s, Longitude: %s, Count: %d', 41.847, -87.661, 'two'));
// Expected output: Latitude: 41.847, Longitude: -87.661, Count: 0
与之前回复中的类似解决方案相比,此解决方案一次性完成所有替换,因此不会替换先前替换值的部分。
jsxt、Zippo
此选项更适合。
String.prototype.format = function() {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
var regexp = new RegExp('\\{'+i+'\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
return formatted;
};
使用此选项,我可以替换如下字符串:
'The {0} is dead. Don\'t code {0}. Code {1} that is open source!'.format('ASP', 'PHP');
使用您的代码,不会替换第二个{0}。;)
从上的ES6可以使用模板字符串:
let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!"
请注意,模板字符串由反引号而不是(单)引号包围。
更多信息:
https://developers.google.com/web/updates/2015/01/ES6-Template-Strings
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings
注:查看mozilla站点以查找支持的浏览器列表。