JS does not provide easy-to-use Formatter functions, and character concatenation seems confusing and difficult to read. The following is a simple implementation version of JS (not strictly tested). JS native does not provide easy-to-use Formatter functions, the character concatenation method seems confusing and difficult to read, and is inconvenient to use. I personally feel that the syntax provided in C # is relatively easy to use, such:
String.Format(“Welcome to learn '{0}','{0}' is awesome,you will {1} it!","Javascript","love");
This ordered replacement method is clear and saves the trouble of passing repeated parameters when you want to replace the same content. Below is a simple JS implementation version (no strict test ):
(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:
args.reduce(execReplace,sourceStr);
The reduce function of Array is used here. reduce and reduceRight are newly added functions of es5. the parameters of this function are reduce (callback, initialValue), and callback receives the following four parameters:
Previusvalue:
If initivalValue is specified, initivalValue is directly used when traversing the first entry into the callback function. If initivalValue is not specified, the first element of the array is used.
The second and later traversal. This value is the result returned by the previous traversal.
The result returned by the last traversal is used as the return value of the reduce function.
CurrentValue: the current item to be traversed.
Index: subscript of the current item in the array
Array: original array
During each execution of 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 the replaced content is traversed in sequence.
Note: The reduceRight and reduce functions are basically the same, but their traversal order is from right to left.