js 格式化字符串
String.prototype.format = function(...args) {
if (args.length == 1 && typeof args[0] == 'object') {
let k = '', v = ''
return this.replace(/{[A-Za-z]+}/g, (it, i) => {
k = it.slice(1, -1)
v = args[0][k]
return typeof v != 'undefined' ? v : '';
})
}
return this.replace(/{(d+)}/g, (it, i) => {
return typeof args[i] != 'undefined' ? args[i] : '';
});
};
console.log("我是{0},今年{1}了. {2}".format("zhgl", 42, 0))
console.log("我是{name},今年{age}了.".format({ name: "zhgl", age: 42 }))