This article describes how to simulate and implement C # String using javascript. the format function is applicable to C # string. the format function is used in many places, so Javascript is used to implement a simple version:
The Code is as follows:
String. format = function ()
{
Var formatStr = arguments [0];
If (typeof formatStr = 'string ')
{
Var pattern,
Length = arguments. length;
For (var I = 1; I <length; I ++)
{
Pattern = new RegExp ('\ {' + (I-1) + '\}', 'G ');
FormatStr = formatStr. replace (pattern, arguments [I]);
}
} Else
{
FormatStr = '';
}
Return formatStr;
};
The above Code adds a static format Method to the javascript String class, and its usage is exactly the same as the string. format of c #. The test is as follows:
The Code is as follows:
String. format ('HTTP: // wcf.open.a.com/blog/sitehome/paged/%0%/%1%',1,20)
Output: "http://wcf.open.a.com/blog/sitehome/paged/1/20"
The Code is as follows:
String. format ('{0} + {0} + {1} = {2}', 1, 1 + 1 + 2)
Output: "1 + 1 + 2 = 4"
The Code is as follows:
String. format ({name: 'leonwang'}, 'Hello, World ')
Output :""
If the first parameter is not of the string type, an empty string is returned without further processing.