4.字符串的遍歷器接口
ES6 為字符串添加了遍歷器接口(詳見《Iterator》一章),使得字符串可以被for...of循環(huán)遍歷。
for (let codePoint of 'foo') {
? console.log(codePoint)
}
// "f"
// "o"
// "o"
除了遍歷字符串,這個遍歷器最大的優(yōu)點是可以識別大于0xFFFF的碼點,傳統(tǒng)的for循環(huán)無法識別這樣的碼點。
let text = String.fromCodePoint(0x20BB7);
for (let i = 0; i < text.length; i++) {
? console.log(text[i]);
}
// " "
// " "
for (let i of text) {
? console.log(i);
}
// "??"
上面代碼中,字符串text只有一個字符,但是for循環(huán)會認為它包含兩個字符(都不可打印),而for...of循環(huán)會正確識別出這一個字符。
7.includes(), startsWith(), endsWith()
傳統(tǒng)上,JavaScript 只有indexOf方法,可以用來確定一個字符串是否包含在另一個字符串中。ES6 又提供了三種新方法。
includes():返回布爾值,表示是否找到了參數(shù)字符串。
startsWith():返回布爾值,表示參數(shù)字符串是否在原字符串的頭部。
endsWith():返回布爾值,表示參數(shù)字符串是否在原字符串的尾部。
let s = 'Hello world!';
s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true
這三個方法都支持第二個參數(shù),表示開始搜索的位置。
let s = 'Hello world!';
s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false
上面代碼表示,使用第二個參數(shù)n時,endsWith的行為與其他兩個方法有所不同。它針對前n個字符,而其他兩個方法針對從第n個位置直到字符串結(jié)束。
8.repeat()
repeat方法返回一個新字符串,表示將原字符串重復(fù)n次。
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
參數(shù)如果是小數(shù),會被取整。
'na'.repeat(2.9) // "nana"
如果repeat的參數(shù)是負數(shù)或者Infinity,會報錯。
'na'.repeat(Infinity)
// RangeError
'na'.repeat(-1)
// RangeError
但是,如果參數(shù)是 0 到-1 之間的小數(shù),則等同于 0,這是因為會先進行取整運算。0 到-1 之間的小數(shù),取整以后等于-0,repeat視同為 0。
'na'.repeat(-0.9) // ""
參數(shù)NaN等同于 0。
'na'.repeat(NaN) // ""
如果repeat的參數(shù)是字符串,則會先轉(zhuǎn)換成數(shù)字。
'na'.repeat('na') // ""
'na'.repeat('3') // "nanana"
9.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一共接受兩個參數(shù),第一個參數(shù)用來指定字符串的最小長度,第二個參數(shù)是用來補全的字符串。
如果原字符串的長度,等于或大于指定的最小長度,則返回原字符串。
'xxx'.padStart(2, 'ab') // 'xxx'
'xxx'.padEnd(2, 'ab') // 'xxx'
如果用來補全的字符串與原字符串,兩者的長度之和超過了指定的最小長度,則會截去超出位數(shù)的補全字符串。
'abc'.padStart(10, '0123456789')
// '0123456abc'
如果省略第二個參數(shù),默認使用空格補全長度。
'x'.padStart(4) // '? x'
'x'.padEnd(4) // 'x? '
padStart的常見用途是為數(shù)值補全指定位數(shù)。下面代碼生成 10 位的數(shù)值字符串。
'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"
11.模板字符串
模板字符串(template string)是增強版的字符串,用反引號(`)標識。它可以當作普通字符串使用,也可以用來定義多行字符串,或者在字符串中嵌入變量。
// 普通字符串
`In JavaScript '\n' is a line-feed.`
// 多行字符串
`In JavaScript this is
not legal.`
console.log(`string text line 1
string text line 2`);
// 字符串中嵌入變量
let name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
上面代碼中的模板字符串,都是用反引號表示。如果在模板字符串中需要使用反引號,則前面要用反斜杠轉(zhuǎn)義。
let greeting = `\`Yo\` World!`;
如果使用模板字符串表示多行字符串,所有的空格和縮進都會被保留在輸出之中。
$('#list').html(`
<ul>
? <li>first</li>
? <li>second</li>
</ul>
`);
上面代碼中,所有模板字符串的空格和換行,都是被保留的,比如<ul>標簽前面會有一個換行。如果你不想要這個換行,可以使用trim方法消除它。
$('#list').html(`
<ul>
? <li>first</li>
? <li>second</li>
</ul>
`.trim());
模板字符串中嵌入變量,需要將變量名寫在${}之中。
function authorize(user, action) {
? if (!user.hasPrivilege(action)) {
? ? throw new Error(
? ? ? // 傳統(tǒng)寫法為
? ? ? // 'User '
? ? ? // + user.name
? ? ? // + ' is not authorized to do '
? ? ? // + action
? ? ? // + '.'
? ? ? `User ${user.name} is not authorized to do ${action}.`);
? }
}
大括號內(nèi)部可以放入任意的 JavaScript 表達式,可以進行運算,以及引用對象屬性。
let x = 1;
let y = 2;
`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"
`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"
let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// "3"
模板字符串之中還能調(diào)用函數(shù)。
function fn() {
? return "Hello World";
}
`foo ${fn()} bar`
// foo Hello World bar
如果大括號中的值不是字符串,將按照一般的規(guī)則轉(zhuǎn)為字符串。比如,大括號中是一個對象,將默認調(diào)用對象的toString方法。