模板字符串
模板字符串(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, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
str += send[i];
}
return str;
}
let send = '<script>alert("abc")</script>'; // 恶意代码
let message = filterHTML`<p>${send}</p>`;
console.log(message) // <p><script>alert("abc")</script></p>
参考文献
阮一峰老师的 ECMAScript 6 入门
点赞 评论 收藏 ~~ 今天的学习记录暂时到这...... ~~ 点赞 评论 收藏