JS analog C # string formatting operation
/***
* * Function: string format substitution operation
***/
String.prototype.format = function () {
var args = arguments;
Return This.replace (/\{(\d+) \}/g,
function (M, i) {return
args[i];
}
JS implements the string processing function format () similar to C #:
Familiar with C # should know that there is a format () such a method, the following to imitate, in JavaScript also implement this feature.
The code example 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
;
}
var fiststr= "{0} welcome you, hope everybody can get want of {1}";
var secondstr= "{WebName} welcome you, hope everybody can get want of {favoriate}";
var Firstout=fiststr.format ("", "something");
var Secondout=secondstr.format ({webName: "", Favoriate: "Something"});
Console.log (firstout);
The above code is to achieve the desired effect, the following describes its implementation process:
I. Principle of realization:
The principle is relatively simple, here to make a long story short, see code comments. Use regular expressions to find the strings to be replaced, and then replace them with the specified content, where the specified content is either a string literal or an object's property value.
Two. Code comments:
1.string.prototype.format=function (args) {}) Adds an instance method format to a string object through a prototype object, which is used to process strings.
2.if (arguments.length>0), if the number of pass parameters is greater than 0.
3.var Result=this, the reference to this is assigned to the variable result.
4.if (arguments.length==1&&typeof (args) = = "Object") is used to determine whether the passed parameter is an object direct amount.
5.for (Var key in args), traversing the attributes in the object's direct volume.
The 6.var reg=new RegExp ("({+key+"}) "," G ") is used to match the specified string.
7.result=result.replace (Reg,args[key]), replaces the matching string with the property value.
8.else{}, if the pass is not a direct amount of an object.
9.for (Var i=0;i<arguments.length;i++), traversing the passed parameters.
10.if (arguments==undefined), if undefined, returns an empty string.
11.var reg=new RegExp ("({[" +i+]}) "," G "), to match the specified string.
12.result=result.replace (reg,arguments), for replacement.
13.return result, returns the replacement string.
14.return this, if no arguments are passed, the string itself is returned.