Code for simulating the C # String. format function in javascript

Source: Internet
Author: User

C # string. format is used in many places, so Javascript is used to implement a simple version:

Copy codeThe 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:

Copy codeThe 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 codeThe Code is as follows:
String. format ('{0} + {0} + {1} = {2}', 1, 1 + 1 + 2)
Output: "1 + 1 + 2 = 4"

Copy codeThe 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.