我正在寻找一个与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()的一个版本,但我们不希望该框架的全部开销。
当前回答
除了zippoxer的答案,我还使用了这个函数:
String.prototype.format = function () {
var a = this, b;
for (b in arguments) {
a = a.replace(/%[a-z]/, arguments[b]);
}
return a; // Make chainable
};
var s = 'Hello %s The magic number is %d.';
s.format('world!', 12); // Hello World! The magic number is 12.
我还有一个非原型版本,我经常使用它的类似Java的语法:
function format() {
var a, b, c;
a = arguments[0];
b = [];
for(c = 1; c < arguments.length; c++){
b.push(arguments[c]);
}
for (c in b) {
a = a.replace(/%[a-z]/, b[c]);
}
return a;
}
format('%d ducks, 55 %s', 12, 'cats'); // 12 ducks, 55 cats
ES 2015更新
ES 2015中所有酷炫的新功能让这一切变得更加简单:
function format(fmt, ...args){
return fmt
.split("%%")
.reduce((aggregate, chunk, i) =>
aggregate + chunk + (args[i] || ""), "");
}
format("Hello %%! I ate %% apples today.", "World", 44);
// "Hello World, I ate 44 apples today."
我想,因为这和以前的一样,实际上并不能解析字母,所以最好只使用一个标记%%。这样做的好处是显而易见的,并且不会使使用单一的%变得困难。但是,如果出于某种原因需要%%,则需要将其替换为自身:
format("I love percentage signs! %%", "%%");
// "I love percentage signs! %%"
其他回答
这不是sprintf的精确复制;然而,它是类似的,并且更强大:https://github.com/anywhichway/stringformatter
使用此库的格式表达式采用嵌入式Javascript对象的形式,例如。
format("I have {number: {currency: "$", precision:2}}.",50.2);
将返回“我有50.20美元”。
/**
* 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];
}
);
}
jsxt、Zippo
此选项更适合。
String.prototype.format = function() {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
var regexp = new RegExp('\\{'+i+'\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
return formatted;
};
使用此选项,我可以替换如下字符串:
'The {0} is dead. Don\'t code {0}. Code {1} that is open source!'.format('ASP', 'PHP');
使用您的代码,不会替换第二个{0}。;)
此方法适用于{0}、{1}和{}。
String.prototype.format = function format()
{
var msg = this;
for(var i in arguments)
msg = msg.replace(/\{\}/,arguments[i]).replace(new RegExp('\\{'+i+'\\}','g'),arguments[i]);
return msg;
}
我开始将Java String.format(实际上是新的Formatter().format))移植到javascript。初始版本位于:
https://github.com/RobAu/javascript.string.format
您可以简单地添加javscript并调用StringFormat.format(“%.2f”,[2.4]);等
请注意,尚未完成,但欢迎反馈:)