ES6加強(qiáng)了對(duì)字符串的擴(kuò)展椎木,這里小編只對(duì)在工作中會(huì)用到或者重要的部分進(jìn)行總結(jié)丘跌。
1思恐、for...of遍歷字符串
for (let codePoint of 'foo') {
console.log(codePoint)
}
// "f"
// "o"
// "o"
es6為字符串添加了遍歷器接口,使得字符串可以被for...of進(jìn)行循環(huán)遍歷
2涛碑、includes() 判斷一個(gè)字符串或數(shù)組是否包含一個(gè)指定的值
let s = 'Hello world!';
s.includes('o') //true
s.includes('Hello', 6) // false
3、 startsWith(), endsWith() 判斷字符串的頭部和尾部
let s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
4孵淘、repeat()復(fù)制字符串
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) //
5蒲障、padStart(),padEnd()頭部補(bǔ)全和尾部補(bǔ)全
如果某個(gè)字符串不夠指定長(zhǎng)度夺英,就會(huì)在尾部和頭部補(bǔ)全
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
padStart的常見(jiàn)用途是為數(shù)值補(bǔ)全指定位數(shù)晌涕。下面代碼生成 10 位的數(shù)值字符串
'1'.padStart(10, '0') // "0000000001"
'12'.padStart(10, '0') // "0000000012"
'123456'.padStart(10, '0') // "0000123456"
6、模板字符串
從前這樣寫(xiě):
$('#result').append(
'There are <b>' + basket.count + '</b> ' +
'items in your basket, ' +
'<em>' + basket.onSale +
'</em> are on sale!'
);
在ES6中痛悯,可以使用string
來(lái)展示字符串余黎,而變量則可以是一個(gè)${xx}來(lái)標(biāo)識(shí)
$('#result').append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);