JavaScript 引擎会将模板字符串解析成一个函数调用表达式;
接着,这个表达式会被执行,并输出一个最终的字符串。
工作原理:
- 将模板字符串中非 ${} 部分拆分为数组(称为 “字符串数组”);
- 将 ${} 中表达式的计算结果按顺序收集为数组(称为 “值数组”);
- 将这两个数组作为参数传递给标签函数
//模拟最终实现
//`
// My name is ${name}, I'm ${age} years old.
// I'm from China.
//`
const result = tagFn(["My name is ", ", I'm ", " years old.\nI'm from China."], name, age);
const tagFn = (temp, ...args) => {
let str = ''
for(let i = 0; l < temp.length; i++) {
// 这里我就不考虑一些容错情况
str += temp[i] + args[i]
}
return str
}
应用场景:
- 对富文本框进行 html 安全转义,防止 xss 攻击
// 标签函数:对嵌入的 HTML 特殊字符进行转义
function escapeHTML(strings, ...values) {
// strings:模板片段数组
// values:嵌入表达式的值数组(... 是剩余参数语法)
let result = "";
// 遍历片段数组,拼接“片段 + 转义后的值”
strings.forEach((str, index) => {
// 转义 HTML 特殊字符(< > " ' &)
const value = values[index]
? values[index]
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'")
: "";
result += str + value;
});
return result;
}
// 模拟恶意输入(含 HTML 标签)
const maliciousInput = '<script>alert("XSS攻击")</script>';
// 使用标签模板处理
const safeHTML = escapeHTML`用户输入:${maliciousInput}`;
console.log(safeHTML);
// 输出:用户输入:<script>alert("XSS攻击")</script>
// 浏览器会渲染为纯文本,而非执行脚本
- 多语言国际化
// 定义多语言字典
const i18n = {
en: { greeting: "Hello, {name}!", time: "Current time: {time}" },
zh: { greeting: "你好,{name}!", time: "当前时间:{time}" }
};
// 标签函数:根据语言替换文本
function t(lang, strings, ...values) {
// 1. 将模板字符串拼接为“键”(如 "greeting: {name}")
const key = strings.reduce((acc, str, i) => acc + str + (values[i] ? `{${i}}` : ""), "");
// 2. 从字典中获取对应语言的文本
let text = i18n[lang][key] || key;
// 3. 替换文本中的 {0}, {1} 为实际值
values.forEach((val, i) => {
text = text.replace(`{${i}}`, val);
});
return text;
}
// 使用标签模板实现多语言
const userName = "David";
const currentTime = "15:30";
// 英文
const enGreeting = t`en:greeting: ${userName}`;
const enTime = t`en:time: ${currentTime}`;
console.log(enGreeting); // Hello, David!
console.log(enTime); // Current time: 15:30
// 中文
const zhGreeting = t`zh:greeting: ${userName}`;
const zhTime = t`zh:time: ${currentTime}`;
console.log(zhGreeting); // 你好,David!
console.log(zhTime); // 当前时间:15:30
- 兼容性
模板字符串是 ES6 特性,支持所有现代浏览器(Chrome 49+、Firefox 34+、Safari 9.1+)和 Node.js 6.0+。若需兼容 IE 等旧环境,可通过 Babel 转译(将模板字符串转为传统的 + 拼接)。
评论区