function fill(z, w, s) {
w = parseInt(w || 0);
s = String(s);
z = String(z);
let c = w - s.length;
while (c > 0 && z.length) {
s = String(z) + s;
c--;
}
return s;
}
function format(fmt, ...args) {
return fmt.replace(/%(0{0,1})(\d*)(\.{0,1})(\d*)([sdfj])/g, (match, z, w, d, p, s) => {
let v;
switch (s) {
case 's': {
let v = String(args.shift());
v = fill(z || ' ', w || 0, v)
return v
}
case 'd': {
let v = Number(args.shift());
v = fill(z || ' ', w, v)
return v;
}
case 'f': {
let v = Number(args.shift());
if (p) {
v = v.toFixed(p);
}
v = String(v);
if (w) {
let i = v.indexOf('.');
if (i >= 0) {
// 有小数
v = fill(z || ' ', w, v.substr(0, i)) + v.substr(i);
}
else {
v = fill(z || ' ', w, v);
}
}
return v;
}
case 'j': {
let v = JSON.stringify(args.shift());
return v;
}
default:
return match;
}
});
}
console.log(format('The %7s %s cost %05d seconds. val=%04f v=%.3f', 'test', 'run', 10, 12.32, 0.13))
console.log('*************')
输出内容
The test run cost 00010 seconds. val=0012.32 v=0.130
*************
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。