JavaScript-ES6-String Methods

JavaScript-ES6-String相關methods

這篇簡介JavaScript-ES6 String相關methods。

String.fromCodePoint()

1
2
3
4
5
6
7
8
9
在ES5提供String.fromCharCode()方法
String.fromCharCode(0x20BB7) --> 不能識別超過0xFFFF的字元,此例造成溢位(0x20BB7 -> 0x20BB)
// "ஷ"

在ES6提供String.fromCodePoint()方法
String.fromCodePoint(0x20BB7)
// "𠮷"
String.fromCodePoint(0x78, 0x1f680, 0x79) === 'x\uD83D\uDE80y' --> 多個參數會被合併成一個String
// true

String.raw()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// `foo${1 + 2}bar`
// 等同於
String.raw({ raw: ['foo', 'bar'] }, 1 + 2) // "foo3bar"

方法實作:
String.raw = function (strings, ...values) {
let output = '';
let index;
for (index = 0; index < values.length; index++) {
output += strings.raw[index] + values[index];
}

output += strings.raw[index]
return output;
}

includes(), startsWith(), endsWith()

1
2
3
4
5
6
7
8
9
10
11
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

repeat()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""

'na'.repeat(2.9) // "nana" --> 小數會被取整數

若參數是Infinity或負數,RangeError
'na'.repeat(Infinity)
// RangeError
'na'.repeat(-1)
// RangeError

參數是-1 ~ 0的小數,因會取整數運算,故等於0
'na'.repeat(-0.9) // ""
參數是NaN,等同0
'na'.repeat(NaN) // ""

參數若是字串,會轉成數字
'na'.repeat('na') // ""
'na'.repeat('3') // "nanana"

padStart(),padEnd()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'

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

若原字串長度 >= 第一個參數,則return 原字串
'xxx'.padStart(2, 'ab') // 'xxx'
'xxx'.padEnd(2, 'ab') // 'xxx'

字串長度 + 補足字元參數 > 第一個參數長度,則截去補足字元參數
'abc'.padStart(10, '0123456789')
// '0123456abc'

沒有第二個參數,用空格補足
'x'.padStart(4) // ' x'
'x'.padEnd(4) // 'x '

'1'.padStart(10, '0') // "0000000001"
'12'.padStart(10, '0') // "0000000012"
'123456'.padStart(10, '0') // "0000123456"

'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
'09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"

trimStart(),trimEnd()

1
2
3
4
5
const s = '  abc  ';

s.trim() // "abc"
s.trimStart() // "abc "
s.trimEnd() // " abc"