字符串常量基础

在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;',
"'": ''',
'"': '&quot;'
},
oUnescape = {
'&amp;': '&',
'&': '&',
'&lt;': '<',
'<': '<',
'&gt;': '>',
'>': '>',
'&apos;': "'",
''': "'",
'&quot;': '"',
'"': '"'
},
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/

作者知乎/公众号:前端疯

(译文)学习ES6非常棒的特性-字符串常量基础的更多相关文章

  1. (译文)学习ES6非常棒的特性——Async / Await函数

    try/catch 在使用Async/Await前,我们可能这样写: const main = (paramsA, paramsB, paramsC, done) => { funcA(para ...

  2. (译文)学习ES6非常棒的特性-深入研究var, let and const

    Var var firstVar; //firstVar被声明,它的默认值是undefined var secondVar = 2; //secondVar被声明,被赋值2 先看一个例子: var i ...

  3. ES6非常棒的特性-解构

    https://blog.csdn.net/maoxunxing/article/details/79772946

  4. 用简单的方法学习ES6

    ES6 简要概览 这里是ES6 简要概览.本文大量参考了ES6特性代码仓库,请允许我感谢其作者@Luke Hoban的卓越贡献,也感谢@Axel Rauschmayer所作的[优秀书籍]//explo ...

  5. ES6的一些常用特性

    由于公司的前端业务全部基于ES6开发,于是给自己开个小灶补补ES6的一些常用特性.原来打算花两天学习ES6的,结果花了3天才勉强过了一遍阮老师的ES6标准入门(水好深,ES6没学好ES7又来了...) ...

  6. Spring Boot 揭秘与实战(四) 配置文件篇 - 有哪些很棒的特性

    文章目录 1. 使用属性文件2. YAML文件 1.1. 自定义属性 1.2. 参数引用 1.3. 随机数属性 1.4. application-{profile}.properties参数加载 3. ...

  7. ES6中的新特性

    本人最近学习es6一些方法,难免有些手痒,想着能不能将这些方法总结下,如下 1.数组的扩展 1)首先什么是伪数组 无法直接调用数组方法或期望length属性有什么特殊的行为,但仍可以对真正数组遍历方法 ...

  8. ES6的十个新特性

    这里只讲 ES6比较突出的特性,因为只能挑出十个,所以其他特性请参考官方文档: /** * Created by zhangsong on 16/5/20. *///    ***********Nu ...

  9. 深入浅出:了解JavaScript的ES6、ES7新特性

    参照阮一峰博客:http://es6.ruanyifeng.com/#README es6常见题:https://blog.csdn.net/qq_39207948/article/details/8 ...

随机推荐

  1. VBA Excel WideCharToMultiByte Compile error on 64-bit System

    Compile Error: The code in this project must be updated for use on64-bit systems. Please review and ...

  2. 结合实例分析Android MVP的实现

    最近阅读项目的源码,发现项目中有MVP的痕迹,但是自己却不能很好地理解相关的代码实现逻辑.主要原因是自己对于MVP的理解过于概念话,还没有真正操作过.本文打算分析一个MVP的简单实例,帮助自己更好的理 ...

  3. 游戏中实现粒子碰撞,纯java

    package com.totoo.TouhouMassLight;import android.content.Context;import android.graphics.Bitmap;impo ...

  4. 【BZOJ1007】水平可见直线(单调栈)

    [BZOJ1007]水平可见直线(单调栈) 题解 Description 在xoy直角坐标平面上有n条直线L1,L2,...Ln,若在y值为正无穷大处往下看,能见到Li的某个子线段,则称Li为 可见的 ...

  5. 【Luogu3919】可持久化数组(主席树)

    题面戳我 题解 放一个板子在这里 用主席树维护一下每个版本就可以啦... #include<iostream> #include<cstdio> #include<cst ...

  6. luoguP2711 小行星

    题目描述 星云中有n颗行星,每颗行星的位置是(x,y,z).每次可以消除一个面(即x,y或z坐标相等)的行星,但是由于时间有限,求消除这些行星的最少次数. 输入输出格式 输入格式: 第1行为小行星个数 ...

  7. awk多分隔符功能及wc命令案列及企业级应用

    打印最后一行行号: cat -n /etc/services|tail -1 awk '{print NR $0}' oldboy.txt|tail -1 awk '{print NR $0}' /e ...

  8. FCN小小实战

    先说一下前期准备工作:自己的运行环境是Ubuntu16.04+caffe+CPU(这台电脑没有GPU)+python 关于python的搭建就不说了,网上随便一搜,很多参考资源.说一下我配置好caff ...

  9. Spring Boot Actutaur + Telegraf + InFluxDB + Grafana 构建监控平台之应用数据分析

    本节将引入完美的granafa仪表板,在上节的基础上,并提出自己的一些监控数据的总结和看法 你可以有一个类似于这个的Dashboard,会引入监控Zimbra协作 本节环境采用的是centos7系统, ...

  10. flask项目部署到阿里云 ubuntu16.04

    title: flask项目部署到阿里云 ubuntu16.04 date: 2018.3.6 项目地址: 我的博客 部署思路参考: Flask Web开发>的个人部署版本,包含学习笔记. 开始 ...