1024programmer Java JavaScript simulation to implement C#String.format function function code_javascript skills

JavaScript simulation to implement C#String.format function function code_javascript skills

The C# string.format function is used in many places, so I implemented a simple version using js:


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 method format to the Javascript String class, and its usage is exactly the same as c#’s string.format. 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,2,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 string type, simply return an empty string without further processing.

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/631988

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索