ES6 字串乾貨
摘取出ES6中字串的新增乾貨「摘自http://es6.ruanyifeng.com/ 」
牛逼之處
模板字串
1.可寫多行字串
2.使用${}
新增變數
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"
模板字串之中還能呼叫函式
function fn() { return "Hello World"; } `foo ${fn()} bar` // foo Hello World bar
模板字串甚至還能巢狀
const tmpl = addrs => ` <table> ${addrs.map(addr => ` <tr><td>${addr.first}</td></tr> <tr><td>${addr.last}</td></tr> `).join('')} </table> `;
標籤模板:
let total = 30; let msg = passthru`The total is ${total} (${total*1.05} with tax)`; function passthru(literals) { let result = ''; let i = 0; while (i < literals.length) { result += literals[i++]; if (i < arguments.length) { result += arguments[i]; } } return result; } msg // "The total is 30 (31.5 with tax)"
literals引數為非變數組成的陣列,變數原本位置為陣列中各元素之間,上面這個例子展示了,如何將各個引數按照原來的位置拼合回去。
- “標籤模板”的一個重要應用,就是過濾 HTML 字串,防止使用者輸入惡意內容。
實用方法集
1.字串的遍歷器介面
for (let codePoint of 'foo') { console.log(codePoint) } // "f" // "o" // "o"
2.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" 'hello'.repeat(2) // "hellohello" 'na'.repeat(0) // ""
4.padStart(),padEnd()
padStart()
用於頭部補全,
padEnd()
用於尾部補全。
'x'.padStart(5, 'ab') // 'ababx' 'x'.padStart(4, 'ab') // 'abax' 'x'.padEnd(5, 'ab') // 'xabab' 'x'.padEnd(4, 'ab') // 'xaba'
'12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12" '09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"