ES6添加了模块字符串,可以将变量的值插入到字符串中
function authorize(user, action) {
if (!user.hasPrivilege(action)) {
throw new Error(
`User ${user.name} is not authorized to do ${action}.`);
}
}
${user.name}
,${action}
被称为模板替换。
-
${}
中的值可以是任意javascript表达式 - 如果
${}
中的值不是字符串,则会调用toString
转换为字符串 - 如果在模板字符串中显示`,则需要escape:`\
\
模板字符串支持多行显示
$("#warning").html(`
<h1>Watch out!</h1>
<p>Unauthorized hockeying can result in penalties
of up to ${maxPenalty} minutes.</p>
`);
TAG 模板
在模板字符串之前可以加上一个tag,这个tag可以是函数,属性
var message =
SaferHTML`<p>${bonk.sender} has sent you a bonk.</p>`;
上面其实等价于
var message =
SaferHTML(templateData, bonk.sender);
templateData是由模板字符串内${}表达式分隔的字符串的数组,上面的templateData等价于Object.freeze(["<p>", " has sent you a bonk.</p>"]
SafeHtml函数实现如下:
function SaferHTML(templateData) {
var s = templateData[0];
for (var i = 1; i < arguments.length; i++) {
var arg = String(arguments[i]);
// Escape special characters in the substitution.
s += arg.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
// Don't escape special characters in the template.
s += templateData[i];
}
return s;
}
网友评论