The C# string.format function is used in many places, so I implemented a simple version using js:
Copy the code code 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 method format to the javascript String class, and its usage is exactly the same as c#'s string.format. The test is as follows:
Copy the code code 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"
Copy the code code as follows:
String.format('{0}+{0}+{1}={2}',1,2,1+1+2)
Output: "1+1+2=4"
Copy the code code as follows:
String.format({name:'leonwang'},'hello,world')
Output: ""
If the first parameter is not of type string, an empty string is simply returned without further processing.