In the process of project development, we often encounter something that consists of HTML and dynamic data. It is especially tiring to write code. I will share two tips below. First, format the operator String: format the operator *** format the operator ** String. formatfunction (str) {varargsarguments, renewRegExp (%
In the process of project development, we often encounter something that consists of HTML and dynamic data. It is especially tiring to write code. I will share two tips below. The first is the formatting of the operator String: The operator formatting/*** the operator formatting */String. format = function (str) {var args = arguments, re = new RegExp ("%
In the process of project development, we often encounter something that consists of HTML and dynamic data. It is especially tiring to write code. I will share two tips below.
The first is the formatting of the operator string:
Operator formatting
/**
* Event character formatting
*/
String. format = function (str ){
Var args = arguments, re = new RegExp ("% ([1-" + args. length + "])", "g ");
Return String (str). replace (
Re,
Function ($1, $2 ){
Return args [$2];
}
);
};
The above code was copied from the front-end blog of 163. The actual application is quite convenient.
Paste this code in your JS and you can use it directly. How to use it? Let's give an example.
Var temp = "Use % 1 code to implement % 2 ";
Alert (String. format (temp, "JS", "function 1"); // you will be prompted to use JS Code to implement function 1.
Alert (String. format (temp, "PHP", "function 2"); // you will be prompted to use PHP code to implement function 2.
Temp is equivalent to a template. In the format function, name in the template according to the parameter order.
The second is also the formatting of the operator string, but I made a small change. Although the performance may not be so fast, it is more convenient to use, so you don't have to look at the location:
String. formatmodel = function(Str, model ){
For (var k inModel ){
Var re = new RegExp ("{" + k + "}", "g");
Str =Str. replace (re, model [k]);
}
ReturnStr;
}
This method can directly pass the object in. Example:
Var temp = "use {code} code to implement {fun }";
Alert (String. formatmodel (temp, {code: "JS", fun: "function 1 "}));
Alert (String. formatmodel (temp, {code: "PHP", fun: "function 2 "}));
These two tips hope to help you do less tedious things in the development process.