Originated from string.Format() in C#
String. prototype.format = function(args) {
if (arguments.length>0) {
var result = this;
if (arguments.length == 1 && typeof (args) == "object" ) {
for (var key in args) {
var reg=new RegExp ("({" key "})","g");
result = result.replace(reg, args[ key]);
}
}
else {
for (var i = 0; i < arguments.length; i ) {
if(arguments[i]==undefined)
{
return "";
}
else
{
var reg=new RegExp ("({[" i "]})","g");
result = result.replace(reg, arguments[i]);
}
}
}
return result;
}
else {
return this;
}
}
Example:
//Two calling methods
var template1="I am {0}, and I am {1} this year";
var template2="I am {name}, and I am {age} this year. ";
var result1=template1.format("loogn",22);
var result2=template1.format({name:"loogn",age:22});
//Two results They are all "I am loogn, I am 22 this year"
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn