Home > Article > Web Front-end > A super practical knowledge introduction to ES6 strings
This article brings you a very practical knowledge introduction about ES6 strings. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Template string
1. Writable multi-line 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"
The template string is also Functions can be called
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> `;
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 of non-variables, and the original position of the variable is in the array Between each element, the above example shows how to put the various parameters back together according to their original positions.
for (let codePoint of 'foo') { console.log(codePoint) } // "f" // "o" // "o"
let s = 'Hello world!'; s.startsWith('Hello') // true s.endsWith('!') // true s.includes('o') // true
All three methods support the second parameter, indicating the starting position of 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 using the second parameter n, endsWith behaves differently from the other two methods. It targets the first n characters, while the other two methods target from the nth position until the end of the string.
The repeat method returns a new string, which means repeating the original string n times.
'x'.repeat(3) // "xxx" 'hello'.repeat(2) // "hellohello" 'na'.repeat(0) // ""
padStart()
is used for head completion,
padEnd()
is used for tail completion.
'x'.padStart(5, 'ab') // 'ababx' 'x'.padStart(4, 'ab') // 'abax' 'x'.padEnd(5, 'ab') // 'xabab' 'x'.padEnd(4, 'ab') // 'xaba'rrree
The above is the detailed content of A super practical knowledge introduction to ES6 strings. For more information, please follow other related articles on the PHP Chinese website!