我正在寻找一个与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()的一个版本,但我们不希望该框架的全部开销。
当前回答
PHPJS项目为许多PHP函数编写了JavaScript实现。由于PHP的sprintf()函数与C的printf()函数基本相同,所以它们的JavaScript实现应该可以满足您的需求。
其他回答
另一个建议是使用字符串模板:
const getPathDadosCidades = (id: string) => `/clientes/${id}`
const getPathDadosCidades = (id: string, role: string) => `/clientes/${id}/roles/${role}`
jQueryGlobalize项目中还有Globalize.format,这是jQueryUI的官方全球化服务。当您需要具有文化意识的格式时,这很好。
我将添加我自己的发现,这些发现是我问过之后发现的:
number_format(用于千位分隔符/货币格式)sprintf(作者同上)
遗憾的是,sprintf似乎不能像.NET的字符串格式那样处理千位分隔符格式。
我这里有一个稍长的JavaScript格式化程序。。。
可以通过多种方式设置格式:
String.format(输入,args0,arg1,…)String.format(输入,obj)“literal”.格式(arg0,arg1,…)“literal”.format(obj)
此外,如果您使用ObjectBase.prototype.format(例如使用DateJS),它将使用它。
示例。。。
var input = "numbered args ({0}-{1}-{2}-{3})";
console.log(String.format(input, "first", 2, new Date()));
//Outputs "numbered args (first-2-Thu May 31 2012...Time)-{3})"
console.log(input.format("first", 2, new Date()));
//Outputs "numbered args(first-2-Thu May 31 2012...Time)-{3})"
console.log(input.format(
"object properties ({first}-{second}-{third:yyyy-MM-dd}-{fourth})"
,{
'first':'first'
,'second':2
,'third':new Date() //assumes Date.prototype.format method
}
));
//Outputs "object properties (first-2-2012-05-31-{3})"
我还使用了.asFormat作为别名,并进行了一些检测,以防已经存在字符串格式(例如使用MS Ajax Toolkit(我讨厌那个库))。
我有一个非常接近Peter的解决方案,但它涉及数字和对象情况。
if (!String.prototype.format) {
String.prototype.format = function() {
var args;
args = arguments;
if (args.length === 1 && args[0] !== null && typeof args[0] === 'object') {
args = args[0];
}
return this.replace(/{([^}]*)}/g, function(match, key) {
return (typeof args[key] !== "undefined" ? args[key] : match);
});
};
}
也许处理所有深度案件会更好,但对于我的需要来说,这很好。
"This is an example from {name}".format({name:"Blaine"});
"This is an example from {0}".format("Blaine");
PS:如果你在AngularJS这样的模板框架中使用翻译,这个函数非常酷:
<h1> {{('hello-message'|translate).format(user)}} <h1>
<h1> {{('hello-by-name'|translate).format( user ? user.name : 'You' )}} <h1>
en.json是什么样子的
{
"hello-message": "Hello {name}, welcome.",
"hello-by-name": "Hello {0}, welcome."
}