ES6 新增了哪些字符串处理方法
我们都知道在 ES6 之前,我们只能使用 indexOf 来判断字符串是否存在某个字符,现在 ES6 多出了几个比较常用的方法:
includes():返回布尔值,判断是否找到参数字符串。
startsWith():返回布尔值,判断参数字符串是否在原字符串的头部。
endsWith():返回布尔值,判断参数字符串是否在原字符串的尾部。
let?str?=?"Ken,KenNaNa,haha"
str.includes("Ken");?????//?true
str.startsWith("Ken");????//?true
str.endsWith("Ken");??????//?false
str.startsWith("Ken",6)??//?false
字符串补全
padStart:返回新的字符串,表示用参数字符串从头部(左侧)补全原字符串。
padEnd:返回新的字符串,表示用参数字符串从尾部(右侧)补全原字符串。
比较常用的,应该就是使用 padStart
console.log("123".padStart(10,"0"));??//?"0000000123"
模板字符串
模板字符串相当于加强版的字符串,用反引号 `, 除了作为普通字符串,还可以用来定义多行字符串,还可以在字符串中加入变量和表达式。
普通用法
let?string?=?`Hello'\n'world`;
console.log(string);
//?"Hello'
//?'world"
多行字符串
let?string1?=??`Hey,
can?you?stop?angry?now?`;
console.log(string1);
//?Hey,
//?can?you?stop?angry?now?
字符串插入变量和表达式
变量名写在 \${} 中,${} 中可以放入 JavaScript 表达式。
let?name?=?"Mike";
let?age?=?27;
let?info?=?`My?Name?is?${name},I?am?${age+1}?years?old?next?year.`
console.log(info);
//?My?Name?is?Mike,I?am?28?years?old?next?year.
字符串中调用函数
function?f(){
return?"have?fun!";
}
let?string2=?`Game?start,${f()}`;
console.log(string2);??//?Game?start,have?fun!
领取专属 10元无门槛券
私享最新 技术干货