字符串补全长度的方法
两个方法分别是头部补全:padStart(len, str);尾部补全:padEnd(len, str);第一个参数是指定字符串的最小长度,第二个参数是用来补全的字符串。
补全字符串长度的情况有以下几种:
- 情况一:正常
let str = 'abc';
let newStr = str.padStart(6, 'def');
console.log(newStr); // defabc
let newStr1 = str.padEnd(6, 'def');
console.log(newStr1); // abcdef
- 情况二:源字符串的长度 >= 指定的字符串的最小长度,则返回源字符串。
let str = 'hello world';
let newStr = str.padStart(6, 'AAA');
console.log(newStr); // hello world
let newStr1 = str.padEnd(6, 'AAA');
console.log(newStr1); // hello world
- 情况三:(用来补全的字符串长度 + 源字符串长度) > 指定字符串的最小长度,则返回截去超出位数的字符串后的补全字符串。
let str = 'hello';
let newStr = str.padStart(7, 'BBBBB');
console.log(newStr); // BBhello
let newStr1 = str.padEnd(7, 'BBBBB');
console.log(newStr1); // helloBB
- 情况四:若省略第二个参数,则用空格补全。
let str = 'A';
let newStr = str.padStart(10);
console.log(newStr); // " A"
let newStr1 = str.padEnd(10);
console.log(newStr1);// "A "
padStart 常见的用途
为数值补全指定位数。
let str = '110';
let newStr = str.padStart(10, '0');
console.log(newStr); // 0000000110
提示字符串格式。
let str = '10 13:10';
let newStr = str.padStart(16, 'YYYY-MM-DD hh:mm');
console.log(newStr); // YYYY-MM-10 13:10
模版字符串
模版字符串是增强版的字符串,用反引号(`)标识;可以当作普通字符串使用,也可以用来定义多行字符串,还能在字符串中嵌入变量。
// 普通字符串,可使用'\n'换行
let a = `hello world`;
console.log(a); //hello world
let b = `hello\nworld`;
console.log(b);
//hello
//world
// 多行字符串
let str = `name is Bob
age is 18`;
console.log(str);
let str1 = `name is Bob
age is 18`; //空格和缩进都会被保留在输出中
console.log(str1);
// name is Bob
// age is 18
//字符串中嵌入变量:${变量名},若变量名未声明,则报错
let name = 'Bob';
let str = `name is ${name}`;
console.log(str); //name is Bob
若要在模版字符串中使用反引号,则可以使用反斜杠( \ )转义。
let name = 'Bob';
let str = `name is \`${name}\``;
console.log(str); // name is `Bob`
${ }:大括号中不仅能放变量名,还能放JS表达式 / 函数 / 字符串。
// JS表达式
let sex = 1;
let str = `莉莉的性别为${sex === 1?'女性':'男性'}`;
console.log(str); // 莉莉的性别为女性
//函数
function sexFunc(sex){
if(sex === 1){
return '女性';
}else {
return '男性';
}
}
let sex = 0;
let str = `小明的性别为${sexFunc(sex)}`;
console.log(str); // 小明的性别为男性