Home  >  Article  >  Web Front-end  >  JavaScript simulation implements C# String.format function function code_javascript skills

JavaScript simulation implements C# String.format function function code_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:12:321122browse

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

Copy code 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]);
                                         '';
}

           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 code

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"



Copy code

The code is as follows:String.format('{0} {0} { 1}={2}',1,2,1 1 2)Output: "1 1 2=4"



Copy code

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.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn