Using arguments to realize String.Format function _javascript technique under JavaScript

Source: Internet
Author: User
The following excerpt the source code, in-depth analysis of his design to achieve the idea:
Copy Code code as follows:

function Format (string) {
var args = arguments;
var pattern = new RegExp ("% ([1-" + Arguments.length + "])", "G");
return string (String). replace (pattern, function (match, index) {
return Args[index];
});
};

Through the Format function, the following code:
Copy Code code as follows:

Format ("and the"%1 want to know whose%2 "," Papers "," shirt "," wear ");

will return: "and the papers want to know whose shirt".
It's kind of like a C # down String.Format function as a parameter call.
Overall, there seems to be no technical content. But is there really no technical content? Lou Pig boldly according to their own JavaScript and arguments shallow understanding and understanding, again to dissect this procedure:
1, Regular expression
Very cleverly new a regular pattern that matches the number of 1 to argument at the beginning of the%, which is the important precondition for the replacement of the 2nd string below;
2, the Replace function of string
The second parameter of the Replace function is a function, which is very "unexpected". By definition, the variable args is actually arguments, then the index parameter can be obtained by Args[index], and index>=1 and index<arguments.length can guarantee the correctness of the parameters.

The function is so short and powerful that it is Shang to create a huge contrast.
There may be many developers like Lou Pig who are spoiled by C #, who are obsessed with the String.Format of C #. ), a good story pig slightly changed the source code:
Copy Code code as follows:

function Format (string) {
var args = arguments;
var pattern = new RegExp ("{[0-" + arguments.length + "])}", "G");
return string (String). replace (pattern, function (match, index) {
var currentindex = parseint (index);
if (Currentindex + 1 > Args.length | | Currentindex < 0) {
throw new error ("Parameter index error");
}
return Args[currentindex + 1];
});
};
document.write ("and the {0} want to know whose {1}", "Papers", "Shirt") ("Wear"));/curly braces, index starting from 0 ...

This would seem to call the format function just like C # 's writing style.
Finally, the writing time to view this article is in 2008, building pigs in 08 when the awareness is quite high, is spontaneous efforts to learn JavaScript, but the arguments know still very immature, Although it is already known that you can define the Createfunction function in a custom event, use the Createfunction function to construct the parameterless functions to use the event, but it has been depressed "only know its shape, not in fact." After reading Andrew's masterpiece, suddenly enlightened, although unresponsive after the understanding, still feel extremely excited and gratified.

look at Andrew Tetlaw's original. In fact, the following has been pointed out that after the Format function argument exceeds 9, the function does not work, and then the solution is also given:

Eric D. Hi, thanks to that brilliant article. Made a lot of things a lot clearer!
Note:new RegExp ("% ([1-" + Arguments.length + "])", "G"); Would fail passed 9 arguments (the regexp would is "% ([1-10])" So it'll only match%0 and% 1).

I am easy fix would to something like:
function Format (string) {var args = arguments var pattern = new RegExp ("% ([0-9]+)", "G"); return string (String). replace (pattern, function (match, index) {if (index = = 0 | | Index >= args.length) throw "Invalid Index in format string "; return Args[index]; }); };
(Sorry for nitpicking, I understand it's only a example and brevety are the main objective, but its a great function to Have

Posted On:january 20th 2009, 12:01 am

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.