ES6中字符串的擴展

1、查找字符串

在ES5中,能夠使用 indexOf 方法和 lastIndexOf 方法查找字符串:spa

let str = 'hello world';
alert(str.indexOf('o'));   // 4
alert(str.lastIndexOf('o'));   // 7
alert(str.lastIndexOf('z'));   // -1

 ES6中,又新增了3個方法用於特定字符的查找。code

 

一、includes()字符串

該方法傳入一個字符串參數,而後返回一個布爾值,表示是否在指定字符串中找到了該字符串片斷。it

let str = 'hello';
console.log(str.includes('h'));   // true
console.log(str.includes('z'));   // false

 

二、startsWith()console

該方法傳入一個字符串參數,而後返回一個布爾值,表示是否在指定字符串開頭找到了該字符串片斷。ast

let str = 'hello';
console.log(str.startsWith('h'));   // true
console.log(str.startsWith('lo'));   // false

 

三、endsWith()模板

該方法傳入一個字符串參數,而後返回一個布爾值,表示是否在指定字符串末尾找到了該字符串片斷。變量

let str = 'hello';
console.log(str.endsWith('h'));   // false
console.log(str.endsWith('o'));   // true

 

2、操做字符串

一、repeat()方法

對一個字符串進行重複,返回一個新字符串。error

let str = 'ha';
console.log(str.repeat(3));   'hahaha'

參數若是是小數,會被向下取整進行操做。

let str = 'ha';
console.log(str.repeat(2.9));   'haha'

參數若是是負數,會報錯。

let str = 'ha';
console.log(str.repeat(-2));   // error

 

3、模板字符串

ES6引入了模板字符串,用反引號標識( ` ),主要功能有倆個。

一、定義多行字符串。

let str = `hello
hello
hello`;
console.log(str)
// hello
// hello
// hello

二、在字符中嵌入變量,把變量包裹在 ${} 中便可。

var username = 'tom';
alert(`hello ${username}`);   // hello tom
相關文章
相關標籤/搜索