ES6 —— 字符串

Posted xulinjun

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ES6 —— 字符串相关的知识,希望对你有一定的参考价值。

一、字符串的遍历器接口

for(let codePoint of ‘hello‘){
  console.log(codePoint);
}
// h
// e
// l
// l
// o

 

二、模板字符串

let userName = ‘小明‘;
let age = 26;
let result = `我叫${userName},我今年${age}岁。`
console.log(result);   // 我叫小明,我今年26岁。

 

三、includes —— 是否找到了参数字符串

let str = ‘hello world‘;
console.log(str.includes(‘hello‘));   // true
console.log(str.includes(‘hi‘));   // false

 

四、startsWith —— 参数字符串是否在原字符串的头部

let str = ‘hello world‘;
console.log(str.startsWith(‘hello‘));   // true
console.log(str.startsWith(‘world‘));   // false

 

 

五、endsWith —— 参数字符串是否在原字符的尾部

let str = ‘hello world‘;
console.log(str.endsWith(‘hello‘));   // false
console.log(str.endsWith(‘world‘));   // true

 

六、repeat —— 将一个字符串重复 n 次

let str = ‘foo‘;
console.log(str.repeat(3));   // foofoofoo

 

七、padStart —— 补全字符串

如果某个字符串不够指定长度,会在头部补全。

let str = ‘foo‘;
console.log(str.padStart(10, ‘ab‘));   // abababafoo

 

八、padEnd —— 补全字符串

如果某个字符串不够指定长度,会在尾部补全。

let str = ‘foo‘;
console.log(str.padEnd(10, ‘ab‘));   // fooabababa

 

九、trimStart —— 消除字符串头部的空格

let str = ‘   hello‘;
console.log(str.length);   // 8
console.log(str.trimStart().length);   // 5

 

十、trimEnd —— 消除尾部的空格

let str = ‘hello   ‘;
console.log(str.length);   // 8
console.log(str.trimEnd().length);   // 5

 

以上是关于ES6 —— 字符串的主要内容,如果未能解决你的问题,请参考以下文章

ES6 模块串联

ES6解构赋值

ES7-Es8 js代码片段

JavaScript ES6 的let和const

VScode插件推荐

没有名称的Javascript ES6导入[重复]