JS native does not provide convenient Formatter functions, and it looks chaotic and difficult to read by character splicing, and it is very inconvenient to use. I personally feel that the syntax provided in C# is more useful, such as:
String.Format("Welcome to learn '{0}','{0}' is awesome,you will {1} it!","Javascript","love");This sequential replacement method is relatively clear, and when replacing the same content, you can save the situation of passing duplicate parameters. The following is the simple implementation version of JS (without strict testing):
(function(exports) {exports.format = function(){var args = Array.prototype.slice.call(arguments),sourceStr = args.shift();function execReplace(text,replacement,index){return text.replace(new RegExp("//{"+index+"//}",'g'),replacement);}return args.reduce(execReplace,sourceStr);}})(window.utils = window.utils || {});console.log(utils.format("Welcome to learn '{0}','{0}' is awesome,you will {1} it!","Javascript","love"));The key is this sentence:
args.reduce(execReplace,sourceStr);
Here, Array's reduce function is used. Reduce and reduceRight are newly added functions in ES5. The parameters of this function are reduce (callback, initialValue). Callback receives 4 parameters:
PreviousValue:
When traversing the first entry of the callback function, if initialValue is specified, initialValue will be used directly, if no first element of the array is specified, the first element of the array will be used.
The value of the second and subsequent traversals is the result of the previous traversal.
The result returned by the last traversal will be used as the return value of the reduce function.
currentValue: the current item it traversed
index: The index of the current item in the array
array: original array
In each execution in execReplace, the result after the previous replacement is used as the original replacement string, the index of the current item is used as the content to be replaced, and iterates in turn to finally complete the replacement content.
Note: reduceRight is basically the same as reduce function, except that its traversal order is from right to left