学习ES6非常棒的特性-字符串常量基础

字符串常量基础

在ES2015之前我们是这么拼接字符串的:

var result = 10;
var prefix = "the first double digit number I learnt was ";
var assembled = prefix + result.toString();
console.log(assembled); // logs => 'the first double digit number I learnt was 10'

在ES2015我们可以这么做:

var result = 10;
var assembled = `the first double digit number I learnt was ${result}`;
console.log(assembled); // logs => 'the first double digit number I learnt was 10'

通过 ${}引用外部的变量

字符串常量拼接里面遍历

假设我们有一个数组,我们怎么遍历它:

var data = [
  // Data here
];
// loop through the data
data.forEach((datarecord, idx) => {
  // for each record we call out to a function to create the template
  let markup = createSeries(datarecord, idx);
  // We make a div to contain the resultant string
  let container = document.createElement("div");
  container.classList.add("as-Series");
  // We make the contents of the container be the result of the function
  container.innerHTML = markup;
  // Append the created markup to the DOM
  document.body.appendChild(container);
});
function createSeries(datarecord, idx) {
  return `
    <div class="a-Series_Title">${datarecord.Title}</div>
  `;
}

完整的拼接方法类似这样:

function createSeries(datarecord, idx) {
  return `
    <h2 class="a-Series_Title">${datarecord.Title}</h2>
    <p class="a-Series_Description">
      <span class="a-Series_DescriptionHeader">Description: </span>${datarecord.Description}
    </p>
    <div class="a-EpisodeBlock">
      <h4 class="a-EpisodeBlock_Title">First episodes</h4>
    </div>
  `;
}

如果数据里面又有一个数组,怎么遍历?

function createSeries(datarecord, idx) {
  return `
    <h2 class="a-Series_Title">${datarecord.Title}</h2>
    <p class="a-Series_Description">
      <span class="a-Series_DescriptionHeader">Description: </span>${datarecord.Description}
    </p>
    <div class="a-EpisodeBlock">
      <h4 class="a-EpisodeBlock_Title">First episodes</h4>
      ${datarecord.Episodes.map((episode, index) =>
        `<div class="a-EpisodeBlock_Episode">
            <b class="">${index+1}</b>
            <span class="">${episode}</span>
        </div>
        `
      )}
    </div>
`};

ok. 然后打印出来:

Episodes
1 Homecoming
,
2 New Colossus
,
3 Champion
,
4 Away
,
5 Paradise
,
6 Forking Paths
,
7 Empire of Light
,
8 Invisible Self

多了一个默认的逗号,怎么办。

${datarecord.Episodes.map((episode, index) =>
  `<div class="a-EpisodeBlock_Episode">
      <b class="">${index+1}</b>
      <span class="">${episode}</span>
  </div>
  `
).join("")}

通过join方法处理一下就好了。

字符串常量里面用if/else

${datarecord.Ended === true ? `` : `<div class="a-Series_More">More to come!</div>`}

使用返回另外一个值的函数

假设我们有这样一个函数

const add = (a, b) => a + b;
function getRatingsAverage(ratings) {
  return ratings.reduce(add) / ratings.length;
}

这样使用就可以了:

`<div class="a-UserRating">Average user rating: <b class="a-UserRating_Score">${getRatingsAverage(datarecord.UserRatings)}</b></div>`

安全

看一个例子:

var username = 'craig<script>alert("XSS")</' + 'script>';
document.write(`<p>Hi ${username}</p>`);

用户输入了一个js代码,然后我们直接填充到了username里面。这个时候会导致浏览器弹出一个alert。 这样肯定是不行的。

一般我们需要escape方法转义一下,或者用textContent。

// HTML Escape helper utility
var util = (function () {
  // Thanks to Andrea Giammarchi
  var
    reEscape = /[&<>'"]/g,
    reUnescape = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34);/g,
    oEscape = {
      '&': '&amp;',
      '<': '&lt;',
      '>': '&gt;',
      "'": '&#39;',
      '"': '&quot;'
    },
    oUnescape = {
      '&amp;': '&',
      '&#38;': '&',
      '&lt;': '<',
      '&#60;': '<',
      '&gt;': '>',
      '&#62;': '>',
      '&apos;': "'",
      '&#39;': "'",
      '&quot;': '"',
      '&#34;': '"'
    },
    fnEscape = function (m) {
      return oEscape[m];
    },
    fnUnescape = function (m) {
      return oUnescape[m];
    },
    replace = String.prototype.replace
  ;
  return (Object.freeze || Object)({
    escape: function escape(s) {
      return replace.call(s, reEscape, fnEscape);
    },
    unescape: function unescape(s) {
      return replace.call(s, reUnescape, fnUnescape);
    }
  });
}());
// Tagged template function
function html(pieces) {
    var result = pieces[0];
    var substitutions = [].slice.call(arguments, 1);
    for (var i = 0; i < substitutions.length; ++i) {
        result += util.escape(substitutions[i]) + pieces[i + 1];
    }
    return result;
}
var username = "Domenic Denicola";
var tag = "& is a fun tag";
console.log(html`<b>${username} says</b>: "${tag}"`);

以上就是今天的内容,感谢阅读。

更多内容,点击阅读原文:
https://benfrain.com/html-templating-with-vanilla-javascript-es2015-template-literals/
作者知乎/公众号:前端疯
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值