我正在寻找一个与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()的一个版本,但我们不希望该框架的全部开销。
当前回答
一个稍有不同的版本,我更喜欢的版本(这个版本使用{xxx}标记,而不是{0}编号的参数,这更易于自我记录,更适合本地化):
String.prototype.format = function(tokens) {
var formatted = this;
for (var token in tokens)
if (tokens.hasOwnProperty(token))
formatted = formatted.replace(RegExp("{" + token + "}", "g"), tokens[token]);
return formatted;
};
一种变化是:
var formatted = l(this);
它首先调用l()本地化函数。
其他回答
这是https://stackoverflow.com/a/4673436/1258486对于CoffeeScript。
https://gist.github.com/eces/5669361
if String.prototype.format is undefined
String.prototype.format = () ->
_arguments = arguments
this.replace /{(\d+)}/g, (match, number) ->
if typeof _arguments[number] isnt 'undefined' then _arguments[number] else match
我使用一个名为String.format for JavaScript的小型库,它支持大多数格式字符串功能(包括数字和日期格式),并使用.NET语法。脚本本身小于4kB,因此不会产生太多开销。
我在列表中没有看到pyformat,所以我想把它放进去:
console.log(pyformat( 'The {} {} jumped over the {}'
, ['brown' ,'fox' ,'foobar']
))
console.log(pyformat('The {0} {1} jumped over the {1}'
, ['brown' ,'fox' ,'foobar']
))
console.log(pyformat('The {color} {animal} jumped over the {thing}'
, [] ,{color: 'brown' ,animal: 'fox' ,thing: 'foobaz'}
))
从上的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站点以查找支持的浏览器列表。
jQueryGlobalize项目中还有Globalize.format,这是jQueryUI的官方全球化服务。当您需要具有文化意识的格式时,这很好。