我正在寻找一个与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()的一个版本,但我们不希望该框架的全部开销。
当前回答
对于Node.js用户,util.format具有类似printf的功能:
util.format("%s world", "Hello")
其他回答
我使用这个简单的函数:
String.prototype.format = function() {
var formatted = this;
for( var arg in arguments ) {
formatted = formatted.replace("{" + arg + "}", arguments[arg]);
}
return formatted;
};
这与string.format非常相似:
"{0} is dead, but {1} is alive!".format("ASP", "ASP.NET")
JavaScript有“sprintf”,您可以在http://www.webtoolkit.info/javascript-sprintf.html.
我需要更进一步的解决方案。
我可以重用一个模板,不仅在声明中生成字符串,而且在执行时间的随机时间生成字符串。
所以我遇到了这个夹具:
class Texplate{
constructor(...args){
this.data = args;
}
apply(...args){
var text = "";
var i = 0, j = 0, n = this.data.length, m = args.length;
for(;i < n && j < m; i++, j++){
text += this.data[i] + args[j];
}
for (; i < n; i++){
text += this.data[i];
}
for (; j < m; j++){
text += args[j];
}
return text;
}
}
这允许创建一个文本模板,该模板在内部用作数组合并算法,从构造函数中定义的文本数组开始。
使用示例:
var Textplate example = new Texplate("Hello, ", "!");
console.log(example.apply("Frank"));
console.log(example.apply("Mary"));
console.log(example.apply());
console.log(example.apply("Frank", " Have a good day!"));
我很惊讶没有人使用reduce,这是一个本机简洁而强大的JavaScript函数。
ES6(EcmaScript2015)
String.prototype.format=函数(){return[…arguments].reduce((p,c)=>p.replace(/%s/,c),this);};console.log('是%s还是%s?…不,是%s!'。格式('平面','鸟','SOman');
<ES6
function interpolate(theString, argumentArray) {
var regex = /%s/;
var _r=function(p,c){return p.replace(regex,c);}
return argumentArray.reduce(_r, theString);
}
interpolate("%s, %s and %s", ["Me", "myself", "I"]); // "Me, myself and I"
工作原理:
reduce对累加器和数组中的每个元素(从左到右)应用一个函数,以将其减少为单个值。
var _r=函数(p,c){return p.replace(/%s/,c)};控制台日志([“a”,“b”,“c”].reduce(_r,“[%s],[%s]和[%s]”)+'\n',[1,2,3].reduce(_r,“%s+%s=%s”)+'\n',[“cool”,1337,“stuff”].reduce(_r,“%s%s%s”));
一个稍有不同的版本,我更喜欢的版本(这个版本使用{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()本地化函数。