ES6 模板字符串

模板字符串

模板字符串(template string)是增强版的字符串,用反引号(`)标识。

`Hello World`
嵌入变量${}
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";
}
`Say ${fn()} ` // 'Say Hello World'

// 模板字符串写成了一个函数的返回值。
let fuc = (name) => `Hello ${name}!`;
fuc('World')  // "Hello World!"
标签模板(函数特殊调用)

标签模板其实不是模板,而是函数调用的一种特殊形式。“标签”指的就是函数,紧跟在后面的模板字符串就是它的参数。

let x = 2;
let y = 11;

tag`Hello ${ x + y } world ${ x * y }`;
// 等同于
tag(['Hello', 'world', ''], 13, 22);

function tag(Arr, value1, value2) {
  console.log(Arr[0]);
  console.log(Arr[1]);
  console.log(Arr[2]);
  console.log(value1);
  console.log(value2);
  return "complete";
}

tag`Hello ${ a + b } world ${ a * b}`;
// "Hello"
// "world"
// ""
// 13
// 22
// "complete"

console.log`Hello ${ a + b } world ${ a * b }` ;
//  ["hello ", " world ", " "] 13 22

“标签模板”的一个重要应用,就是过滤 HTML 字符串,防止用户输入恶意内容。

function filterHTML(send) {
  let str = send[0];
  for (let i = 1; i < arguments.length; i++) {
    let arg = String(arguments[i]);
    str += arg.replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;");
    str += send[i];
  }
  return str;
}
let send = '<script>alert("abc")</script>'; // 恶意代码
let message = filterHTML`<p>${send}</p>`;
console.log(message) // <p>&lt;script&gt;alert("abc")&lt;/script&gt;</p>

参考文献

阮一峰老师的 ECMAScript 6 入门


点赞 评论 收藏 ~~ 今天的学习记录暂时到这...... ~~ 点赞 评论 收藏
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shaoin_2

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值