Javascript simulation to implement C # String. format function code _ javascript skills

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.