字符串常量基础

在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. Linux显示一行显示列总计

    Linux显示一行显示列总计 youhaidong@youhaidong-ThinkPad-Edge-E545:~$ free -t total used free shared buffers ca ...

  2. ORA-00922:选项缺失或无效

    1.错误描述    ORA-00922:选项缺失或无效 2.错误原因 3.解决办法

  3. T470p VS 2017 上运行 VS 2015 + Qt 5.6.2 + GLSL 400

    vs 2017 的qt设置可以按照这篇文章 注意,必须使用qt的安装程序进行安装,否则会出现意想不到的问题(不要简单地把qt的文件拷贝过来..血的教训) 显卡的问题 好不容易编译通过了,一运行报了一个 ...

  4. freemarker定义一个连续的序列(十九)

    1.简易说明 定义一个连续的序列,并打印出序列中的元素 2.实现源码 <#--freemarker定义了一个连续的序列--> <#assign nums=1..100/> &l ...

  5. Python Cookbook(第3版)中文版:15.15 C字符串转换为Python字符串

    15.15 C字符串转换为Python字符串¶ 问题¶ 怎样将C中的字符串转换为Python字节或一个字符串对象? 解决方案¶ C字符串使用一对 char * 和 int 来表示, 你需要决定字符串到 ...

  6. I/HwPointEventFilter: do not support AFT because of no config

    I/HwPointEventFilter: do not support AFT because of no config 这是华为对系统做了修改,默认不打印日志,要改配置 在拨号界面输入:以下进入工 ...

  7. 【洛谷1607】【USACO09FEB】庙会班车

    题面 题目描述 逛逛集市,兑兑奖品,看看节目对农夫约翰来说不算什么,可是他的奶牛们非常缺乏锻炼--如果要逛完一整天的集市,他们一定会筋疲力尽的.所以为了让奶牛们也能愉快地逛集市,约翰准备让奶牛们在集市 ...

  8. [BZOJ4034] [HAOI2015] T2 (树链剖分)

    Description 有一棵点数为 N 的树,以点 1 为根,且树点有边权.然后有 M 个操作,分为三种: 操作 1 :把某个节点 x 的点权增加 a . 操作 2 :把某个节点 x 为根的子树中所 ...

  9. 46个Linux面试常见问题送给你

    问题一: 绝对路径用什么符号表示?当前目录.上层目录用什么表示?主目录用什么表示? 切换目录用什么命令? 答案:绝对路径: 如/etc/init.d当前目录和上层目录: ./  ../主目录: ~/切 ...

  10. IDEA jsp模板

    > File > Settings- > File and Code Templates > Other >Jsp files >Jsp File.jsp < ...