function formatString(str, ...args) { return str.replace(/{(\d+)}/g, function(match, index) { return typeof args[index] != 'undefined' ? args[index] : match ; }); } var str = "Hello, my name is {0} and I am {1} years old."; var result = formatString(str, "John", 30);
这将创建一个字符串:“Hello, my name is John and I am 30 years old.”