function formatString() {
if (!arguments.length) {
return null;
}
var str = arguments[0];
for (var i = 1; i < arguments.length; i++) {
var placeHolder = '{' + (i - 1) + '}';
var fix = placeHolder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
str = str.replace(new RegExp(fix, 'g'), arguments[i]);
}
return str;
}
例:
formatString("hello,{0}","world");//hello,world
ES6语法
var world = "world";
console.log(`hello,${world}`);//hello,world