es6中标签模板

之所以写这篇文章,是因为标签模板是一个很容易让人忽略的知识点

首先我们已经非常熟悉模板字符串的使用方法

const name = "诸葛亮"
const templateString = `hello, My name is ${
     name}`

标签模板介绍

这里的标签模板其实不是模板,而是函数调用的一种特殊形式

“标签”指的就是函数(函数名),紧跟在后面的模板字符串就是它的参数

比如,下面的代码可以正常运行

alert`hello world`

如果模板字符里面有变量,就不是简单的调用了,而是会将模板字符串先处理成多个参数,再调用函数

const name = '诸葛亮'
const age = 18

console.log`hello ${
     name}, I know your age is ${
     age}`

控制台打印如下
在这里插入图片描述

const name = '诸葛亮'
const age = 18

const tag = (stringArr, ...args) => {
   
    console.log('stringArr', stringArr)
    console.log('args', args)
}

tag`hello ${
     name}, I know your age is ${
     age}`
// 相当于调用函数tag, tag(['hello ', ', I know your age is ', ''], '诸葛亮', 18)

控制台打印如下
在这里插入图片描述

使用场景

  • 过滤 HTML 字符串,防止用户输入恶意内容
function saferHTML(templateData) {
   
  let s = templateData[0];
  for (let i = 1; i < arguments.length; i++) {
   
    let arg = String(arguments[i]);
    s += arg.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
    s += templateData[i];
  }
  return s;
}

const string = '<script>alert("恶意代码")</script>';
const content = saferHTML`<p>${
     sender}富文本内容</p>`;
// <p>&lt;script&gt;alert("恶意代码")&lt;/script&gt;富文本内容</p>
  • 多语言转换
i18n`Welcome to China!`
// "欢迎来到中国!"
  • 将命令式编程转为声明式编程
// 命令式编程
const url = 'xxxxxxx'
a.style.color = "red"
a.style.backgroundColor = 'blue'
a.style.fontSize = '18px'
a.style.lineHeight = '26px'
a.href = `https://${
     url}`
a.target = '_blank'
a.textContent = '点击跳转'

// 声明式编程
a.styles`
	color: red;
	backgroundColor: blue;
	fontSize: 18px;
	lineHeight: 26px;
`.props`
	href: `https://${
   url}`;
	target: '_blank';
`.content`点击跳转`

相关推荐

  1. ES6模板语法与字符串处理

    2024-02-05 02:04:02       40 阅读
  2. common.js和es6模块引入的区别

    2024-02-05 02:04:02       10 阅读
  3. ES6 对象合并

    2024-02-05 02:04:02       31 阅读
  4. ES6的Promise

    2024-02-05 02:04:02       43 阅读
  5. ES6的Set

    2024-02-05 02:04:02       37 阅读
  6. es6常见问题

    2024-02-05 02:04:02       31 阅读
  7. es6 ?? 与 || 区别

    2024-02-05 02:04:02       45 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-02-05 02:04:02       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-02-05 02:04:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-02-05 02:04:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-02-05 02:04:02       18 阅读

热门阅读

  1. 【从浅到深的算法技巧】堆排序,应用

    2024-02-05 02:04:02       25 阅读
  2. 阿里云入门

    2024-02-05 02:04:02       32 阅读
  3. K8s之configMap

    2024-02-05 02:04:02       28 阅读
  4. 常见code review问题

    2024-02-05 02:04:02       31 阅读
  5. MySQL中SQL查询语句优化

    2024-02-05 02:04:02       35 阅读
  6. 开源协议介绍

    2024-02-05 02:04:02       36 阅读
  7. 【华为机试】2023年真题C卷(python)-字符串拼接

    2024-02-05 02:04:02       39 阅读
  8. Docker 大纲

    2024-02-05 02:04:02       29 阅读
  9. 【递归】 92. 反转链表 II

    2024-02-05 02:04:02       33 阅读
  10. h.264与h.263的区别

    2024-02-05 02:04:02       32 阅读