In fact, I don't have C # just to see someone write this function "JS implementation similar to C # string processing method format ()"
I looked at the code, think the idea is cumbersome, so simplify the idea to write a method of the same function, and everyone share the next idea.
Let's look at the code first.
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: "hehe", Fuck: "French gram"})); parameter {0} parameter {1} parameter {3} parameter Oh parameter {ooxx}console.log} parameter {Str.format ({"1": "111", hehe: "hehe", 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 invulnerable, because my thinking is the exact opposite of the original.
The idea is to use a regular match for all format characters in the string, such as {key} , and then replace the key as the object's corresponding key or the corresponding subscript of the array.
The first line var _dic = typeof args = = = = "Object"? Args:arguments; You can accept data in 3 formats.
Multi-parameter: arguments
Array: []
Object: {}
Save the 3 data as a dictionary in the _dic variable.
The following is the replacement of the substitution function, in fact, is to check the dictionary operation.
return _dic[key] | | str;
If the _dic[key] corresponding data exists, it is replaced, otherwise the original data is returned.
Because arguments, [], {} can be processed as a dictionary, it is possible to do so in the simplest way.
At the same time the flaw is also very clear exposure, that is, if the string {key} This is a lot of parameters, but the replacement of the data is very rare, performance certainly not as his method.
But I think the general operation must be the parameter corresponding to replace, so that the performance loss can not worry, because the corresponding parameter, the loss is 0. The
is instead faster than the one he's been replacing more than once.