Extract new dry goods with strings in ES6 http://es6.ruanyifeng.com/」
Bull's eye
Template string
1. Write multiline string
2. Use ${} to add variables
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"
Functions can also be called in the template string
function fn() { return "Hello World"; } `foo ${fn()} bar` // foo Hello World bar
Template strings can even be nested
const tmpl = addrs => ` <table> ${addrs.map(addr => ` <tr><td>${addr.first}</td></tr> <tr><td>${addr.last}</td></tr> `).join('')} </table> `;
Label template:
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)"
The literals parameter is an array composed of non variables. The original position of the variables is between the elements in the array. The above example shows how to combine the parameters according to the original position.
- An important application of "tag template" is to filter HTML strings to prevent users from entering malicious content.
Set of practical methods
1. Traverser interface of string
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
All three methods support a second parameter, indicating where to start the search.
let s = 'Hello world!'; s.startsWith('world', 6) // true s.endsWith('Hello', 5) // true s.includes('Hello', 6) // false
The above code indicates that when the second parameter n is used, endsWith behaves differently from the other two methods. It is for the first n characters, while the other two methods are for the nth position up to the end of the string.
3.repeat()
The repeat method returns a new string, indicating that the original string is repeated n times.
'x'.repeat(3) // "xxx" 'hello'.repeat(2) // "hellohello" 'na'.repeat(0) // ""
4.padStart(),padEnd()
padStart()
For head completion,
padEnd()
For tail completion.
'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"