基于先前建议的解决方案:
// First, checks if it isn't implemented yet.
if (!String.prototype.format) {
String.prototype.format = function() {
var args = arguments;
return this.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
"{0} is dead, but {1} is alive! {0} {2}".format("ASP", "ASP.NET")
输出
ASP已经死了,但 ASP.NET 还活着!销售{2}
如果您不想修改 的原型:String
if (!String.format) {
String.format = function(format) {
var args = Array.prototype.slice.call(arguments, 1);
return format.replace(/{(\d+)}/g, function(match, number) {
return typeof args[number] != 'undefined'
? args[number]
: match
;
});
};
}
为您提供更熟悉的:
String.format('{0} is dead, but {1} is alive! {0} {2}', 'ASP', 'ASP.NET');
具有相同的结果:
ASP已经死了,但 ASP.NET 还活着!销售{2}