字符串常量基础

在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. 7.C++类与封装的概念

    类通常分为以下两部分 -类的内部具体实现 -类的外部使用方法 比如: 用户使用手机,只需要知道如何使用. 而手机开发者,则需要考虑手机内部的实现细节. 类的封装 并不是类的每个成员变量和成员函数都要对 ...

  2. 使用pyh生成HTML文档

    title: 使用pyh生成HTML文档 tags: [python3, 爬虫,pyh] date: 2018-03-09 21:01:34 categories: Python keywords: ...

  3. [Luogu3936]Coloring

    Luogu sol 模拟退火呀 初始状态按顺序涂色,让同种颜色尽量放在一起. 每次随机交换两个位置,注意\(\Delta\)的计算 瞎JB调一下参数就行了 可以多做几次避免陷入局部最优解 code # ...

  4. LCT维护子树信息(BZOJ4530:[BJOI2014]大融合)

    题面 没有权限号的可以去LOJ Sol 大家都知道,\(LCT\)上有许多实边和虚边 实边就是每棵\(Splay\)上的既认父亲又认儿子的边 虚边就是\(Splay\)和\(Splay\)之间只认父亲 ...

  5. linux系统文件系统重要知识介绍

    [root@Asterplus:~]$ls -lhitotal 48K3684713 -rw------- 1 root root 5.9K Jul 1 00:23 anaconda-ks.cfg36 ...

  6. python中Django 使用方法简述

    Django是由Python写成的免费而且开源的Web应用框架--一堆零件的组成,可以帮助我们轻松的开发网站.这些零件都包括常用的:登录(注册,登入,登出),网站后台管理,表单,文件上传等.可以帮助我 ...

  7. 在Debian系列Linux系统Ubuntu上安装配置yum的试验

    用习惯了Red Hat系统的都知道我们习惯于三种安装方式:一种是rpm包的方式安装,一种就是tar包的方式来安装,还有一种方式就是yum源的安装. 首先rpm包的用法,我们一般是在Red Hat光驱里 ...

  8. vue-cli工具搭建vue-webpack项目

    1.安装node环境 下载地址 https://nodejs.org/en/download/ node -v   安装成功后在命令行查看node版本 npm-v   安装成功后在命令行查看npm版本 ...

  9. js备战春招の四の正则表达式详解

    正则表达式语法规则:/正则表达式主体/修饰符(可选)什么是正则表达式:正则表达式是用于匹配字符串中字符组合的模式.在 JavaScript中,正则表达式也是对象.这些模式被用于 RegExp 的 ex ...

  10. 牛客小白月赛1 A-简单题

    描述 Etéreo 是个爱学习的好孩子.在年假期间,他依然热情于数学.他最近发现了一个高大上的东西:,他觉得这里的  非常的厉害!然后他又告诉你:,,他会告诉你  和  ,想请你告诉他  的值.当然这 ...