3.1 嵌套表达式
在模板字符串中,可以使用任何表达式,包括函数调用、三元运算符和模板字符串嵌套。
示例:
在表达式 ${a + b} 中执行数学运算,并将结果插入到字符串 result中。
JavaScript
const a = 5;
const b = 10;
const result = `The result of ${a} + ${b} is ${a + b}.`;
console.log(result); // "The result of 5 + 10 is 15."
3.2 嵌套模板字符串
模板字符串可以嵌套,这样可以创建复杂的字符串。
示例:
对象 user 中的方法 greet() 的调用嵌套在模板字符串 message 中。
JavaScript
const user = {
name: 'Bob',
age: 25,
greet() {
return `Hello, ${this.name}!`;
}
};
const message = `${user.greet()} You are ${user.age} years old.`;
console.log(message); // "Hello, Bob! You are 25 years old."
3.3 标签模板字符串 (Tagged Templates)
标签模板字符串允许调用函数来处理模板字符串。这可以对字符串进行额外的操作,比如国际化、安全插入HTML等。
语法:
function tag(strings, ...values) {
// 处理字符串和值
return 结果;
}
const result = tag`Тemplate string with ${variable}`;
示例:
函数 highlight() 处理字符串和值,将值包裹在带有类 highlight 的HTML标签 <span> 中。
JavaScript
function highlight(strings, ...values) {
return strings.reduce((result, str, i) =>
`${result}${str}${values[i] || ''}`, '');
}
const name = 'Carol';
const hobby = 'painting';
const message = highlight`My name is ${name} and I love ${hobby}.`;
console.log(message);
// "My name is <span class="highlight">Carol</span> and I love <span class="highlight">painting</span>."
3.4 安全插入值
模板字符串可以帮助避免一些常见的安全问题,比如 XSS(跨站脚本),通过安全地插入值。这在将用户数据插入HTML时尤其有用。
示例:
函数 safeHTML() 替换值中的危险字符,防止 XSS 攻击。
JavaScript
function safeHTML(strings, ...values) {
return strings.reduce((result, str, i) =>
`${result}${str}${String(values[i]).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')}`, '');
}
const userInput = '<script>alert("XSS")</script>';
const message = safeHTML`User input: ${userInput}`;
console.log(message);
// "User input: <script>alert("XSS")</script>"
GO TO FULL VERSION