JS native does not provide a convenient use of the formatter function, the use of character stitching method looks confusing and difficult to read, and it is inconvenient to use. Personally feel the syntax provided in C # is more useful, such as:
1 |
String.Format ("Welcome to learn ' {0} ', ' {0} ' is awesome,you'll {1} it!", "Javascript", "Love"); |
This is a sequential replacement, more clear, and when you want to replace the same content can be omitted to pass the repeated parameters, the following is a simple implementation of JS version (no rigorous testing):
02 |
Exports.format = function () { |
03 |
var args = Array.prototype.slice.call (arguments), |
04 |
Sourcestr = Args.shift (); |
06 |
function Execreplace (text,replacement,index) { |
07 |
Return Text.replace (New RegExp ("{" +index+ "}", ' G '), replacement); |
10 |
Return Args.reduce (EXECREPLACE,SOURCESTR); |
12 |
}) (Window.utils = Window.utils | | {}); |
14 |
Console.log (Utils.format ("Welcome to learn ' {0} ', ' {0} ' is awesome,you'll {1} it!", "Javascript", "Love")); |
The key is the sentence:
1 |
Args.reduce (EXECREPLACE,SOURCESTR); |
The reduce function of the array is used here, and reduce and reduceright are the newly added functions of ES5, the parameter of the function is reduce (callback,initialvalue), and the callback receives 4 parameters, respectively:
Previousvalue:
When traversing the callback function for the first time, if Initivalvalue is specified, the initivalvalue is used directly if the first element that will use the array is not specified
Second and subsequent traversal the value is the result of the previous traversal return
The result returned by the last traversal will be the return value of the reduce function
CurrentValue: The current item traversed to
Index: Subscript of the current item in an array
Array: Original array
Use the result of the previous substitution as the original replacement string for each execution in Execreplace, using the index of the current item as the content to be replaced, traversing sequentially, and finally completing the replacement.
Note: Reduceright is basically the same as the reduce function, except that its traversal order is from right to left