ES6 笔记 模板字符串

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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容