您好,欢迎访问一九零五行业门户网

ES6字符串超实用的知识介绍

本篇文章给大家带来的内容是关于es6字符串超实用的知识介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
模板字符串
1.可写多行字符串
2.使用${}添加变量
let x = 1;let y = 2;`${x} + ${y} = ${x + y}`// 1 + 2 = 3`${x} + ${y * 2} = ${x + y * 2}`// 1 + 4 = 5let 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') // trues.endswith('!') // trues.includes('o') // true
这三个方法都支持第二个参数,表示开始搜索的位置。
let s = 'hello world!';s.startswith('world', 6) // trues.endswith('hello', 5) // trues.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字符串超实用的知识介绍的详细内容。
其它类似信息

推荐信息