我正在寻找一个与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()的一个版本,但我们不希望该框架的全部开销。
当前回答
我需要一个函数,它可以以用户喜欢的方式格式化价格(以美分为单位),而棘手的是,格式是由用户指定的——我不希望我的用户理解类似printf的语法或regexp等。我的解决方案与Basic中使用的解决方案有些相似,因此用户只需使用数字的#位置进行标记,例如:
simple_format(1234567,"$ ###,###,###.##")
"$ 12,345.67"
simple_format(1234567,"### ### ###,## pln")
"12 345,67 pln"
我相信这很容易被用户理解,也很容易实现:
function simple_format(integer,format){
var text = "";
for(var i=format.length;i--;){
if(format[i]=='#'){
text = (integer%10) + text;
integer=Math.floor(integer/10);
if(integer==0){
return format.substr(0,i).replace(/#(.*#)?/,"")+text;
}
}else{
text = format[i] + text;
}
}
return text;
}
其他回答
当前JavaScript
从上的ES6可以使用模板字符串:
let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!"
详见下文Kim的回答。
较旧的答案
试试JavaScript的sprintf()。
如果你真的想自己做一个简单的格式化方法,不要连续替换,而是同时替换。
因为当先前替换的替换字符串也包含如下格式序列时,提到的大多数其他建议都会失败:
"{0}{1}".format("{1}", "{0}")
通常,您希望输出为{1}{0},但实际输出为{1}{1}}。所以要像恐惧噬菌体的建议那样同时进行替换。
您可以使用此功能
String.prototype.format = function (args) {
var str = this;
return str.replace(String.prototype.format.regex, function(item) {
var intVal = parseInt(item.substring(1, item.length - 1));
var replace;
if (intVal >= 0) {
replace = args[intVal];
} else if (intVal === -1) {
replace = "{";
} else if (intVal === -2) {
replace = "}";
} else {
replace = "";
}
return replace;
});
};
String.prototype.format.regex = new RegExp("{-?[0-9]+}", "g");
// Sample usage.
var str = "She {1} {0}{2} by the {0}{3}. {-1}^_^{-2}";
str = str.format(["sea", "sells", "shells", "shore"]);
alert(str);
从上的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站点以查找支持的浏览器列表。
现在,有一个名为locatus的包,它将其他语言的函数转换为Javascript,如php、python、ruby等。
const printf = require('locutus/php/strings/printf')
printf('Hello world');
你可以试试这个游乐场代码沙盒
我用这个:
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!");