我正在寻找一个与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()的一个版本,但我们不希望该框架的全部开销。
当前回答
我很惊讶没有人使用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”));
其他回答
+1 Zippo,但函数体需要如下所示,否则它会在每次迭代时附加当前字符串:
String.prototype.format = function() {
var formatted = this;
for (var arg in arguments) {
formatted = formatted.replace("{" + arg + "}", arguments[arg]);
}
return formatted;
};
我没有看到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;
});
};
另一个建议是使用字符串模板:
const getPathDadosCidades = (id: string) => `/clientes/${id}`
const getPathDadosCidades = (id: string, role: string) => `/clientes/${id}/roles/${role}`
当前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}}。所以要像恐惧噬菌体的建议那样同时进行替换。
我使用模板文字方法,如下所示:
export const messages = {
foo: (arg1, arg2) => `Hello ${arg1} ${arg2}`,
bar: (arg1) => `Hello ${arg1}`,
}
从文件中:
console.log(messages.foo('Bar', 'World'))
console.log(messages.bar('Foo'))