1、字符串的遍歷
ES6為字符串添加了遍歷接口,使得字符串可以被 for...of
循環遍歷。
for( let i of 'bar' ) {
console.log( i );
}
// b
// a
// r
除了遍歷字符串,這個遍歷器最大的優點是可以識別大于
0xFFFF1的碼點,傳統的
for`循環無法識別這樣的碼點。
var text = String.fromCodePoint(0x20BB7);
for (let i = 0; i < text.length; i++) {
console.log(text[i]);
}
// " "
// " "
for (let i of text) {
console.log(i);
}
// "??"
2、includes(),startsWith(),endsWith()
傳統上,JavaScript只有indexOf
方法,可以用來確定一個字符串是否包含在另一個字符串中。ES6又提供了三種新方法。
- includes():返回布爾值,表示是否找到了參數字符串。
- startsWith():返回布爾值,表示參數字符串是否在源字符串的頭部。
- endsWith():返回布爾值,表示參數字符串是否在源字符串的尾部。
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
上面代碼表示,使用第二個參數n
時,endsWith
的行為與其他兩個方法有所不同。它針對前n
個字符,而其他兩個方法針對從第n
個位置直到字符串結束。
3、repeat()
repeat
方法返回一個新字符串,表示將原來字符串重復n
次。
"x".repeat(3); // "xxx"
"diu".repeat(2); // "diudiu"
"he".repeat(0); // ""
注:repeat
的參數一般都是傳正整數
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'
padStart的常見用途是為數值補全指定位數。下面代碼生成10位的數值字符串。
'1'.padStart(10, '0') // "0000000001"
'12'.padStart(10, '0') // "0000000012"
'123456'.padStart(10, '0') // "0000123456"
另一個用途是提示字符串格式。
'05'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-05"
'05-10'.padStart(10, 'YYYY-MM-DD') // "YYYY-05-10"
5、模板字符串
傳統的JavaScript語言,輸出模板通常是這樣寫的。
$('#result').append(
'There are <b>' + basket.count + '</b> ' +
'items in your basket, ' +
'<em>' + basket.onSale +
'</em> are on sale!'
);
上面這種寫法相當繁瑣不方便,ES6引入了模板字符串解決這個問題。
$('#result').append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
模板字符串(template string)是增強版的字符串,用反引號(`)標識。它可以當作普通字符串使用,也可以用來定義多行字符串,或者在字符串中嵌入變量。
let name = "xxb", time = "today";
`Hello ${name}, how are you ${time}?`
// "Hello xxb, how are you today?"
上面代碼中的模板字符串,都是用反引號表示。如果在模板字符串中需要使用反引號,則前面要用反斜杠轉義。
let greeting = `\`Yo\` World!`;
如果使用模板字符串表示多行字符串,所有的空格和縮進都會被保留在輸出之中。
$('#list').html(`
<ul>
<li>first</li>
<li>second</li>
</ul>
`);
大括號內部可以放入任意的JavaScript表達式,可以進行運算,以及引用對象屬性。
var x = 1;
var y = 2;
`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"
`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"
var obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// 3
模板字符串甚至還能嵌套。
const tmpl = addrs => `
<table>
${addrs.map(addr => `
<tr><td>${addr.first}</td></tr>
<tr><td>${addr.last}</td></tr>
`).join('')}
</table>
`;
上面代碼中,模板字符串的變量之中,又嵌入了另一個模板字符串,使用方法如下。
const data = [
{ first: '<Jane>', last: 'Bond' },
{ first: 'Lars', last: '<Croft>' },
];
console.log(tmpl(data));
// <table>
//
// <tr><td><Jane></td></tr>
// <tr><td>Bond</td></tr>
//
// <tr><td>Lars</td></tr>
// <tr><td><Croft></td></tr>
//
// </table>
————
前端·小b
紙上學來終覺淺,絕知此事要躬行