js-模板字面量及应用

拆解字符串和变量

let desc = 'something'
let desc2 = 'something'
function bar () {
  return function foo (string, ...values) {
    console.log(string) // 前后字符串
    console.log(values) // 变量
    // [ 'EveryThing is ', '! But you not ', '!' ]
    // [ 'something', 'something' ]
  }
}
bar()`EveryThing is ${desc}! But you not ${desc2}!`

function tag (strings, ...values) {
  return strings.reduce(function (s, v, idx) {
    // s 为变量前字符串
    // v 为变量后字符串
    // values[idx - 1]是字符串下面对应的变量的值,思路基本都是对该值进行各种润饰处理。
    return s + (idx > 0 ? values[idx - 1] : '') + v
  }, '')
}
// let text = tag`EveryThing is ${desc}!`
let text = tag`EveryThing is ${desc}! But you not ${desc2}!`
console.log(text)

应用

  1. 转美元
function dollabillsyall (strings, ...values) {
  return strings.reduce(function (s, v, idx) {
    if (idx > 0) {
      if (typeof values[idx - 1] == 'number') {
        s += `$${values[idx - 1].toFixed(2)}`
      } else {
        s += values[idx - 1]
      }
    }
    return s + v
  })
}
let amt1 = 11.11
let amt2 = amt1 * 1.01
let custorm = "hjj"
let msg = dollabillsyall`Thanks for your purchase, ${custorm}! Your product cost was ${amt1}, which with tax comes out to ${amt2}`
console.log(msg)
  1. 过滤html
function safeHtml (strings, ...values) {
  return strings.reduce(function (s, v, idx) {
    return s + String(values[idx - 1]).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, '&gt;') + v
  })
}

let content = '<script>alert(1)</script>'
let html = safeHtml`${content} is safe html`
console.log(html)
  1. 多语言转换
function il8nCh (strings, ...values) {
  let langugeMap = new Map([
    ['red', '红'],
    ['blue', "蓝"],
    ['yellow', "黄"],
  ])
  return strings.reduce((s, v, idx) => s + langugeMap.get(values[idx - 1]) + v)
}
function il8nFrench (strings, ...values) {
  let langugeMap = new Map([
    ['red', 'Rouge'],
    ['blue', "Bleu"],
    ['yellow', "Jaune"],
  ])
  return strings.reduce((s, v, idx) => s + langugeMap.get(values[idx - 1]) + v)
}
let blue = 'blue'
let yellow = 'yellow'
let red = 'red'
let sendMsg = il8nCh`按钮的颜色有${red},${yellow},${blue}`
let sendMsg2 = il8nFrench`Les couleurs des boutons sont:${red},${yellow},${blue}`
console.log(sendMsg)
console.log(sendMsg2)

String.raw
String.raw的应用,反向组装字符串。与模板字面量对应

将拆解的字符串和变量组合起来,逆向第一个例子。
// String.raw({raw: ['msg1', 'msg2', ..., '']}, var1, var2, ...)
console.log(String.raw({ raw: ['EveryThing is ', '! But you not ', ''] }, desc, desc2))

// 过滤html+raw
function safeHtmlraw (strings, ...values) {
  // return strings.reduce(function (s, v, idx) {
  //   return s + String(values[idx - 1]).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, '&gt;') + v
  // })
  
  // string 这个作为数组传人
  // values 单独处理变量
  values = values.map(item => {
    item = String(item).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, '&gt;')
    return item
  })
  // 处理好变量后直接丢回去,思路清晰明了。
  return String.raw({ raw: strings }, ...values)
}

let content1 = '<script>alert(1)</script>'
let content2 = '<script>alert(2)</script>'
let htmls = safeHtmlraw`${content1} is safe html, ${content2} too!`
console.log(htmls)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值