问题描述
我正在寻找一个很好的JavaScript等价的C / PHP printf()
或C#/ Java程序员, String.Format( )
( IFormatProvider
for .NET)。
I'm looking for a good JavaScript equivalent of the C/PHP printf()
or for C#/Java programmers, String.Format()
(IFormatProvider
for .NET).
我的基本要求是千位分隔符现在的数字格式,但处理许多组合(包括日期)的东西会很好。
My basic requirement is a thousand separator format for numbers for now, but something that handles lots of combinations (including dates) would be good.
我意识到微软的库提供了 String.Format()
的版本,但我们不知道我不想要那个框架的全部开销。
I realize Microsoft's Ajax library provides a version of String.Format()
, but we don't want the entire overhead of that framework.
推荐答案
编辑:从ES6上你可以使用模板字符串:
From ES6 on you could use template strings:
let soMany = 10;
console.log(`This is ${soMany} times easier!`);
// "This is 10 times easier!
参见Kim的以获取详细信息。
See Kim's answer below for details.
尝试使用。
更新好的,如果您真的想自己做一个简单的格式化方法,请不要连续进行替换,同时执行这些操作。
Update Ok, if you really want to do a simple format method on your own, don’t do the replacements successively but do them simultaneously.
因为前面替换的替换字符串也包含如下格式序列,所以提到的大多数其他提议都会失败:
Because most of the other proposals that are mentioned fail when a replace string of previous replacement does also contain a format sequence like this:
"{0}{1}".format("{1}", "{0}")
通常你会期望输出 {1} {0}
但是实际输出是 {1} {1}
。所以请同时替换,如。
Normally you would expect the output to be {1}{0}
but the actual output is {1}{1}
. So do a simultaneously replacement instead like in fearphage’s suggestion.
这篇关于JavaScript等效于printf / String.Format的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!