1. 程式人生 > >字串的擴充套件

字串的擴充套件

1、字串的遍歷器介面

ES6 為字串添加了遍歷器介面,使得字串可以被for...of迴圈遍歷。

//字串迴圈 for  of
for(let s of  'helloworld'){    
  console.log(s)  //h e l l ....
};

2、includes(), startsWith(), endsWith()

  • includes():返回布林值,表示是否找到了引數字串。
  • startsWith():返回布林值,表示引數字串是否在原字串的頭部。
  • endsWith():返回布林值,表示引數字串是否在原字串的尾部
let s = 'Hello world!
'; s.startsWith('Hello') // true s.endsWith('!') // true s.includes('o') // true

這三個方法都支援第二個引數,表示開始搜尋的位置。

let s = 'Hello world!';

s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false

上面程式碼表示,使用第二個引數n時,endsWith的行為與其他兩個方法有所不同。它針對前n個字元,而其他兩個方法針對從第n個位置直到字串結束。

3、repeat()

repeat方法返回一個新字串,表示將原字串重複n次。

'x'.repeat(3) // "xxx"
'na'.repeat(0) // ""
'na'.repeat(2.9) // "nana" 取小數會向下取整

//如果repeat的引數是負數或者Infinity,會報錯。
'na'.repeat(Infinity)
// RangeError
'na'.repeat(-1)
// RangeError

但是,如果引數是 0 到-1 之間的小數,則等同於 0,這是因為會先進行取整運算。0 到-1 之間的小數,取整以後等於-0repeat視同為 0。

'na'.repeat(-0.9) // ""
'na
'.repeat(NaN) // "" NaN等同有0 'na'.repeat(true) // "na" ture等同於1 'na'.repeat(false) // "" ture等同於0 'na'.repeat('2') //"nana" 字串先轉換成數字

4、padStart(),padEnd()

ES2017 引入了字串補全長度的功能。如果某個字串不夠指定長度,會在頭部或尾部補全。padStart()用於頭部補全,padEnd()用於尾部補全。

//原字串長度小於指定長度
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'

//原字串長度大於指定長度
'xxx'.padStart(2, 'ab') // 'xxx'
'xxx'.padEnd(2, 'ab') // 'xxx'

如果用來補全的字串與原字串,兩者的長度之和超過了指定的最小長度,則會截去超出位數的補全字串。

'abc'.padStart(10, '0123456789')
// '0123456abc'

如果省略第二個引數,預設使用空格補全長度。

'x'.padStart(4) // '   x'
'x'.padEnd(4) // 'x   '

5、模板字串

模板字串(template string)是增強版的字串,用反引號(`)標識。

模板字串中嵌入變數,需要將變數名寫在${}之中。

$('#result').append(`There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>are on sale!`);