时间: 2020-08-30|tag:67次围观|0 条评论

ES6模板字面量(template literal)

多行字符串

ES5情况下多行字符串

多行的字符串以 逗号 ' 开头,以逗号 ' 结尾,并且每一行的空格末尾接一个 反斜杠 『\』('转义符')。且需要换行

let longStr = 'a \long \long \story'console.log(longStr)// a long long story

以上的繁琐的操作最后只是一个书写上的多行样式,其实打印出来的字符串的值还是单行。但是在ES6中字符串用 一对反引号 `` 包住,存在换行 空白等 最终也会保留下来

?

let longStr = `alonglongstory`console.log(longStr)/*alonglongstory*/

ES6的多行字符的应用:

在需要获取一些数据,如播放列表 商品列表之类的首先就需要构造一个由HTML组成的字符串,然而这个过程除了层层嵌套还特容易出错(单引号 双引号 变量),并且最终拼接成的 HTML 也是没有换行与缩进的

?产品列表-可编辑

var html = `        <li class="product">          <div class="cover">             <a href="javascript:;" class="">X</a>                                           </div>          <a href="javascript:;">            <figure>              <img src=${product.img}  alt="">              <figcaption class="name">Macbook xxx</figcaption>              <figcaption class="price">${product.price}</figcaption>            </figure>          </a>        </li>        `.trim()

HTML中新获取数据的HTML的真正的格式:

ES6-字符串模板与字符串新增的方法插图
ES6多行字符串的应用

ES6的多行模式,把上面HTML构成的字符串稍微的改动即可,因为 一对反引号 `` 包裹字符串,存在换行最终也会保留。只需要用用String.prototype.trim()去除首尾多余的空白就行

var html = `<li class="product">  <div class="cover">    <a href="javascript:;" class="">X</a>  </div>  <a href="javascript:;">    <figure>      <img src="'+product.img+'"  alt="">      <figcaption class="name">Macbook xxx</figcaption>      <figcaption class="price">+product.price+</figcaption>    </figure>  </a></li>`.trim()// Sting.prototype.trim()去除拼接成的字符串两边的多余的空白位置
字符串插值

在ES5中,变量要插入字符串中,就必须用 + 加号 连接前后的字符串。ES6中只需要把变量(JavaScript表达式都可以),放入 ${} 即可。

?

let name = 'Alex'let sth = '书'let info = `这是 ${name} 的 ${sth}`console.log(info)// 这是 Alex 的 书

且ES6字符串插值可嵌套

{} 嵌套的内部用 `` 包裹,嵌套部分的变量依旧用{} 包住

?

let info1 = `这就是就是 ${`${name} 的 ${sth}`}`console.log(info1)// 这就是就是 Alex 的 书

标签化模板(template Tag)

对模板字面量进行转换并返回最终的字符串值,且这里的 标签tag 指的是『特殊的函数』,tagpara

?

function tag(literals, value1, value2) {  // debugger  console.log(literals[0])  console.log(literals[1])  console.log(literals[2])  console.log(value1)  console.log(value2) }let name = 'Lemon'let age = 18const personInfo = tag`${name} is ${age}`console.log(personInfo)

tag函数的第一个参数是一个数组,该数组的成员是模板字符串中那些没有变量替换的部分,第一个参数后面的参数这得是被 ${}包裹的变量的部分

可以通过对 tag函数 debugger与上面其打印内部的参数来证实

debugger:

ES6-字符串模板与字符串新增的方法插图2
标签化模板字符串debugger

打印内部参数:

ES6-字符串模板与字符串新增的方法插图3
标签化模板字符串的参数

⚠️:如果标签模板的函数的参数的 首位与末尾都是一个 ${} 包裹的变量,则:

literals[0] === '' literals[literals.length -1] === ''

应用:把标签模板的参数重新编排,显示在屏幕上:

function printTag(literals, ...values) {  let str = ''  const newValues = values.map(value => `<span class="values">${value}</span>`)    literals.reduce((prev, literal, i) => str += `${literal}${newValues[i] || ''}`, '')  // 使用Array.prototype.reduce()注意,不要忘记参数 previousValue  // 因为printTag的第一个参数 literals.length - 1 === values.length,所以newValues[literals.length - 1] === undefined,所以使用 『newValues[i] || '' 』,确保newValues[literals.length - 1]的值为空字符而不是 undefined  return str}const v1 = 'Lemon'const v2 = 'Apple'const personInfo = printTag` ${v1} litersla1 ${v2}literals2`document.body.innerHTML = personInfo

效果:

ES6-字符串模板与字符串新增的方法插图4
标签化模板的demo.png

ES6字符串新增的常用方法

ES6常见新增的方法 endsWith() startsWith() includes() repeat()

示例代码?

let info = 'Be Patience!'
  • startsWith()

给定的 参数(字符串) 在 字符串的『起始位置』则返回 true,否则返回 false

console.log(info.startsWith('Be')) // trueconsole.log(info.startsWith('B'))  // trueconsole.log(info.startsWith('x')) //false

注意:如果存在两个参数,startsWith(str, index)的参数index指的是在字符串内部 起始 位置

console.log(info.startsWith('P', 3)) // true// 即在index为 info.indexOf('P')的位置,为startWith('P', 3)开始的位置console.log(info.startsWith('at', 4)) // true

应用?:可用于筛选指定开头的字符串:

// 一组人的生日信息let Info = { Tommy: "19891019", Holiday: "19921011", Jelly: "199303133"}

需求:筛选出 1990-1999年出生的成员

分析: 用String.prototype.startWith() 判断Info[key]字符串的开头是 '199' 即可。显然如果用ES5的方法就有点麻烦

function gt90s(obj) {  let arr = []  for (let key in obj) {    if (obj[key].startsWith('199')) {      arr.push(key)    }  }   return arr}gt90s(Info)// ["Holiday", "Jelly"]
  • includes()

给定的 参数(字符串) 被包含在字符串的『内部』,包含则返回 true,否则返回 false

console.log(info.includes('Pa')) // trueconsole.log(info.includes(' ')) // trueconsole.log(info.includes('Le')) // false

应用includes在某些情况下,可以替代 String.prototype.indexOf(str)

? 判断'hello world!'是否包含'hello'

  • ES5的方法:
var info = 'hello world!'info.indexOf('hello') !== -1
  • ES6的方法
let info = 'hello world!'info.includes('hello') // true

相比 indexOf() includes()方法显得更加便捷。但是indexOf() 可以得出查找的字符串在源字符串中的具体位置

  • endsWith()

给定的 参数(字符串) 在字符串的『末尾』,包则返回 true,否则返回 false

console.log(info.endsWith('!')) // trueconsole.log(info.endsWith('ce!')) // trueconsole.log(info.endsWith('xx!')) //false

注意:如果endsWith(str, index)存在两个参数,则用法和上面的有区别*。index可以理解为在源字符串的 起始位置 截取一个长度为index的“新字符”,然后查找 “新字符”的 末尾是否为 str。

  • repeat()

给定的参数为 字符串重复 的次数,返回一个将 原字符串 指定重复次数的新字符串

'?'.repeat(8)// "????????"' '.repeat(8)// "        "

需求: 可以用于控制台打印的右对齐

实现?

let str = 'aaaaaaa'let str1 = 'xxxxxxxxx'function alignRight(str, len=28) {  var space = len - str.length  console.log(space)  return `${' '.repeat(Math.max(space, 0))}${str}`}alignRight(str)// "                     aaaaaaa"alignRight(str1)// "                   xxxxxxxxx"
ES6-字符串模板与字符串新增的方法插图5
String.prototype.repaet()

参考:

阮一峰-ES6 入门教程

Understanding ECMAScript 6(简体中文版)

mqyqingfeng/Blog-ES6系列之模板字符串


版权声明:本文为博主原创文章,未经博主许可不得转载

文章转载于:https://www.jianshu.com/p/b054b026f442

原著是一个有趣的人,若有侵权,请通知删除

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自起风了,原文地址《ES6-字符串模板与字符串新增的方法
   

还没有人抢沙发呢~