用来补全字符串长度的方法
基本用法
str.padStart(length, string);
str.padEnd(length, string);
length: 补全后的字符串总长度
string: 用来补全的字符串内容
const str = 'x';
console.log(str.padStart(5, 'ab')); // ababx
console.log(str.padEnd(5, 'ab')); // xabab
console.log(str.padEnd(6, 'ab')); // xababa
注意事项
1.原字符串的长度,等于或大于最大长度,不会消减原字符串,字符串补全不生效,返回原字符串:
const str = 'xxx';
console.log(str.padStart(2, 'ab')); // xxx
console.log(str.padEnd(2, 'ab')); // xxx
2.用来补全的字符串与原字符串长度之和超过了最大长度,截去超出位数的补全字符串,原字符串不动:
const str = 'abc';
console.log(str.padStart(10, '0123456789')); //0123456abc
console.log(str.padEnd(10, '0123456789')); // abc0123456
3.如果省略第二个参数,默认使用空格补全长度
const str = 'x';
console.log(str.padStart(4)); // x
console.log(str.padEnd(4)); //x