Home > Web Front-end > JS Tutorial > string.format function code in js_javascript skills

string.format function code in js_javascript skills

WBOY
Release: 2016-05-16 18:04:41
Original
1575 people have browsed it

Originated from string.Format() in C#

Copy code The code is as follows:

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:
Copy code The code is as follows:

//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"
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template