我正在寻找一个与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()的一个版本,但我们不希望该框架的全部开销。
当前回答
我没有看到String.format变体:
String.format = function (string) {
var args = Array.prototype.slice.call(arguments, 1, arguments.length);
return string.replace(/{(\d+)}/g, function (match, number) {
return typeof args[number] != "undefined" ? args[number] : match;
});
};
其他回答
我在列表中没有看到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'}
))
现在,有一个名为locatus的包,它将其他语言的函数转换为Javascript,如php、python、ruby等。
const printf = require('locutus/php/strings/printf')
printf('Hello world');
你可以试试这个游乐场代码沙盒
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()等的链接)
/**
* 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];
}
);
}
虽然不是世界上最推荐的功能,但它确实有效。
如果需要sprintf,只需复制并粘贴相同的函数,并将return console.log(sb)更改为只返回sb。
printf=函数(s,/*args…*/){a=参数;al=a.length;如果(al<=1)返回-2;如果(al>=2&&s.toLowerCase().search(/%[a-z]/)==-1)返回-1;sb=s;对于(i=1;i<=al-1;i++){sb=某人替换(/%[a-z]/,a[i]);}返回控制台日志(sb);}var someString=“您好%s\n现在是%s:%s%s。\n今天是%s\n”;printf(someString,“StackOverflowUser”,“5”,“48”,“PM”,“漂亮”);