1. 程式人生 > >字符串的擴展

字符串的擴展

取整 空格 template comm 如果 blog 變量 字符串 概述

概述

ES6增加了對字符串的擴展。

1.字符串的遍歷器接口

ES6為字符串添加了遍歷器接口,使得字符串可以被for...of循環遍歷。

for (let codePoint of ‘foo‘) {
  console.log(codePoint)
}
// "f"
// "o"
// "o"

2.includes(), startsWith(), endsWith()

  • includes():返回布爾值,表示是否找到了參數字符串。
  • startsWith():返回布爾值,表示參數字符串是否在原字符串的頭部。
  • endsWith():返回布爾值,表示參數字符串是否在原字符串的尾部。
var s = ‘Hello world!‘;

s.startsWith(‘Hello‘) // true
s.endsWith(‘!‘) // true
s.includes(‘o‘) // true

這三個方法支持第二個參數,表示開始搜索的位置。

var s = ‘Hello world!‘;

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

使用第二個參數n時,endsWith的行為與其他兩個方法有所不同。它針對前n個字符,而其他兩個方法針對從第n個位置直到字符串結束。

3.repeat()

‘x‘.repeat(3) // "xxx"
‘hello‘.repeat(2) // "hellohello"
‘na‘.repeat(0) // ""

參數如果是小數,會被取整。
‘na‘.repeat(2.9) // "nana"

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


如果參數是0到-1之間的小數,則等同於0,這是因為會先進行取整運算。0到-1之間的小數,取整以後等於-0,repeat視同為0。
‘na‘.repeat(-0.9) // ""

參數NaN等同於0
‘na‘.repeat(NaN) // ""

如果repeat的參數是字符串,則會先轉換成數字。
‘na‘.repeat(‘na‘) // ""
‘na‘.repeat(‘3‘) // "nanana".

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‘

//padStart和padEnd一共接受兩個參數,第一個參數用來指定字符串的最小長度,第二個參數是用來補全的字符串。

‘xxx‘.padStart(2, ‘ab‘) // ‘xxx‘
‘xxx‘.padEnd(2, ‘ab‘) // ‘xxx‘

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

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

//如果省略第二個參數,默認使用空格補全長度。
‘x‘.padStart(4) // ‘   x‘
‘x‘.padEnd(4) // ‘x   ‘

5.模板字符串

ES6中引入了模板字符串(Template Literal),是創建字符串的一種新方法。有了這個新特性,我們就能更好地控制動態字符串。這將告別長串連接字符串的日子。

1.多行字符串

let myStr = `hello
world`;
console.log(myStr)   //hello
                     //world

2.表達式

let nameVal = ‘xiaoli‘;
let str = `my name is ${nameVal}`
console.log(str)   //my name is xiaoli

相關鏈接

1.ES6簡介

2.let和const命令

3.變量的解構賦值

參考資料

1.阮一峰的《ES6入門》

字符串的擴展