我正在寻找一个与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()本地化函数。
其他回答
当前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}}。所以要像恐惧噬菌体的建议那样同时进行替换。
/**
* Format string by replacing placeholders with value from element with
* corresponsing index in `replacementArray`.
* Replaces are made simultaneously, so that replacement values like
* '{1}' will not mess up the function.
*
* Example 1:
* ('{2} {1} {0}', ['three', 'two' ,'one']) -> 'one two three'
*
* Example 2:
* ('{0}{1}', ['{1}', '{0}']) -> '{1}{0}'
*/
function stringFormat(formatString, replacementArray) {
return formatString.replace(
/\{(\d+)\}/g, // Matches placeholders, e.g. '{1}'
function formatStringReplacer(match, placeholderIndex) {
// Convert String to Number
placeholderIndex = Number(placeholderIndex);
// Make sure that index is within replacement array bounds
if (placeholderIndex < 0 ||
placeholderIndex > replacementArray.length - 1
) {
return placeholderIndex;
}
// Replace placeholder with value from replacement array
return replacementArray[placeholderIndex];
}
);
}
JavaScript中的数字格式
我来到这个问题页面,希望找到如何在JavaScript中格式化数字,而不引入另一个库。以下是我的发现:
舍入浮点数
JavaScript中sprintf(“%.2f”,num)的等价物似乎是num.toFixed(2),它将num格式化为2位小数,并带舍入(但请参见@ars265下面关于Math.round的评论)。
(12.345).toFixed(2); // returns "12.35" (rounding!)
(12.3).toFixed(2); // returns "12.30" (zero padding)
指数形式
sprintf(“%.2e”,num)的等效值为num.toExponential(2)。
(33333).toExponential(2); // "3.33e+4"
十六进制和其他基数
要以基数B打印数字,请尝试num.toString(B)。JavaScript支持从基数2到36的自动转换(此外,某些浏览器对base64编码的支持有限)。
(3735928559).toString(16); // to base 16: "deadbeef"
parseInt("deadbeef", 16); // from base 16: 3735928559
参考页
JS数字格式快速教程
toFixed()的Mozilla参考页(带有指向Precision()、toExponential()、toLocaleString()等的链接)
有了sprintf.js,你可以制作一个漂亮的小格式
String.prototype.format = function(){
var _args = arguments
Array.prototype.unshift.apply(_args,[this])
return sprintf.apply(undefined,_args)
}
// this gives you:
"{%1$s}{%2$s}".format("1", "0")
// {1}{0}
String.prototype.format=函数(){var final=字符串(this);for(设i=0;i<arguments.length;i++){final=final.replace(“%s${i+1}”,参数[i])}return final |“”}console.log((“hello%s2 how%s3 you%s1”).format('hi','hello','how'));<h1 id=“text”></h1>