Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 17:12:32
Original
1166 people have browsed it

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.
Related labels:
c#
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template