字元串的擴充
1.字元串的周遊器接口
- 字元串可以被for...of循環周遊。
與es5的比較
for循環雖可以周遊字元串,但不能識别大于oxFFFF的編碼;
2.位置 --> 字元/碼點
根據指定位置傳回對應的字元和碼點
es5:
- charCodeAt() 碼點
- charAt() 字元
es6: ---優勢,能識别大于oxFFFF的編碼;
- codePointAt()--傳回碼點
- at()--傳回字元 (目前es6還未實作,需要通過墊片庫實作)
let hhh='fdf';
hhh.charAt(1);
// "d"
hhh.charCodeAt(1);
// 100
hhh.codePointAt(1);
// 100
hhh.at(1)
// Uncaught TypeError: hhh.at is not a function
3.碼點 --> 字元
根據碼點傳回對應的字元
- es5:String.fromCharCode(0x20BB7); 定義在String對象上
- es6:String.fromCodePoint();定義在字元串的執行個體對象上。--能識别32位字元。即能識别Unicode編号大于oxFFFF;
String.fromCharCode(100)
"d"
String.fromCodePoint(0x20BB7)
// "?"
String.fromCodePoint(100,100,100)
// ddd
4.查詢字元串是否包含某個字元
es5:
- indexOf()
es6:
- includes():傳回布爾值,表示是否找到了參數字元串。
- startsWith():傳回布爾值,表示參數字元串是否在原字元串的頭部。
- endsWith():傳回布爾值,表示參數字元串是否在原字元串的尾部
都支援第二個參數,表示開始搜尋的位置。
let s = 'Hello world!';
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false
5.repeat(n)
傳回一個新字元串,表示将原字元串重複n次。
參數如果是小數,會被取整。
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
'na'.repeat(2.9) // "nana"
'na'.repeat(Infinity)
// RangeError
'na'.repeat(-1)
// RangeError
參數NaN等同于 0
6.字元串補全長度的功能
padStart(minlength,string)用于頭部補全,
padEnd(minlength,string)用于尾部補全
用途:
- 提示字元串格式;
- 為數值補全指定位數
'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'
'x'.padStart(4) // ' x'
'x'.padEnd(4) // 'x '
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"