學習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/
作者知乎/公衆號:前端瘋
這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章