本篇文章给大家带来的内容是关于ES6字符串超实用的知识介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。 模板字符串 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" 以上就是ES6字符串超实用的知识介绍的详细内容,更多请关注模板之家(www.mb5.com.cn)其它相关文章! |