Example of the Format function of C # implemented in JavaScript

Source: Internet
Author: User

Editor: Today to share a JS implementation of similar C # format method. The formatted output of the string is helpful to the string conversion and formatting display.

Body:

Directly on the code:

The code is as follows Copy Code
String
. Prototype.format =
function
(args)
{

Var
_dic =
typeof
args = =
"Object"
? Args:
Arguments
;

Return

This
. replace (
/\{([^{}]+) \}/g
,
function
(STR, key)
{

Return
_dic[key] | | Str
});
}
Var
str =
parameter {0} parameter {1} parameter {3} parameter {hehe} parameter {{fuck}} parameter {Ooxx}]
;
Console.log (Str.format (
"001"
,
"002"
) );
Parameter 001 parameter 002 parameter {3} parameter {hehe} parameter {{fuck}} parameter {Ooxx}
Console.log (Str.format ([
"001"
,
"002"
]) );
Parameter 001 parameter 002 parameter {3} parameter {hehe} parameter {{fuck}} parameter {Ooxx}
Console.log (Str.format ({hehe:
Oh
, Fuck:
"The law of the Gram"
}) );
parameter {0} parameter {1} parameter {3} parameter hehe parameter {} parameter {Ooxx}
Console.log (Str.format ({
"1"
:
"111"
, hehe:
Oh
, Ooxx:
haha
}) );

parameter {0} parameter 111 parameter {3} parameter hehe parameter {{fuck}} parameter haha
The code is simple to understand, easy to maintain, and supports parameter substitution in 3 different formats.
But it is not unassailable, because my ideas are completely opposite to the original.

The idea is this, using the regular match out of the string all {key} such as the format character, and then the key as the corresponding key or array corresponding subscript to replace.
The first line of var _dic = typeof args = = "Object"?  args:arguments; Data can be accepted in 3 formats.
Multi-parameter: arguments
Arrays: []
Object: {}
Keep these 3 kinds of data as dictionaries in the _dic variable.

The following is a replacement function, in fact, is to do dictionary operation.
return _dic[key] | | Str
If the _dic[key] corresponds to the data, replace it or return the original data.
Because arguments, [], {} can be treated as a dictionary, it is possible to achieve this effect in the simplest way.

At the same time, the flaw is very clearly exposed, that is, if the string {key} This parameter is very much, but the replacement of the data is very small, the performance is certainly not the way he did.
But I think the general operation is definitely a parameter corresponding to replace, so the performance loss is not to worry, because the corresponding parameters, loss is 0.
Instead of the one he's been replacing more than once.

Test the top of the Firefox under the problem, because Firefox's global is not quite the same as IE and the change here

The code is as follows Copy Code

var str = "{0}aaa,b{{0}}bb,d{{a}}dd,c{{{0}}}cc{{0}},{{{{1},aaa,{1}}}}},ccc,{1}eee,{{1}},{{2}}\" ccc\ ""
var str = "{0} {1}:AAA:CCC"
var data = ["Tx{1}t1", "tx{{0}}t2"];
str = StringFormat (str, data);
alert (str);

function StringFormat (str, list) {
var data = list;
var strarray = Str.split ("");
for (var i = 0; i < data.length; i++) {
var Strreg = "(\\{+" + i + "\\}+)";
var reg = new RegExp (Strreg, "G");

while (true) {
var exec = reg.exec (str);
if (null = EXEC)
Break

var start = Exec[0].match (/{+/g);
var end = Exec[0].match (/}+/g);
var findStr = Exec[0].replace (/{{/g, "{"). Replace (/}}/g, "}");
var lastindex = Exec.index + exec[0].length;

            for (var strindex = Exec.index; Strindex < lastindex; strindex++) {
                Strarray[strindex] = "";
           }

if (start[0].length% 2 > 0 &&
End[0].length% 2 > 0) {
Strarray[exec.index] = Findstr.replace (/{\d+}/g, data[i));
}
else {
Strarray[exec.index] = findStr;
}
}
}

str = Strarray.join ("");

return str;
}

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.