转自:https://developers.google.com/web/updates/2015/01/ES6-Template-Strings

Strings in JavaScript have been historically limited, lacking the capabilities one might expect coming from languages like Python or Ruby. ES6 Template Strings (available in Chrome 41+), fundamentally change that. They introduce a way to define strings with domain-specific languages (DSLs), bringing better:

  • String interpolation
  • Embedded expressions
  • Multiline strings without hacks
  • String formatting
  • String tagging for safe HTML escaping, localization and more.

Rather than stuffing yet another feature into Strings as we know them today, Template Strings introduce a completely different way of solving these problems.

Syntax

Template Strings use back-ticks (``) rather than the single or double quotes we're used to with regular strings. A template string could thus be written as follows:

 
var greeting = `Yo World!`;

So far, Template Strings haven't given us anything more than normal strings do. Let’s change that.

String Substitution

One of their first real benefits is string substitution. Substitution allows us to take any valid JavaScript expression (including say, the addition of variables) and inside a Template Literal, the result will be output as part of the same string.

Template Strings can contain placeholders for string substitution using the ${ } syntax, as demonstrated below:

 
// Simple string substitution
var name = "Brendan";
console.log(`Yo, ${name}!`); // => "Yo, Brendan!"

As all string substitutions in Template Strings are JavaScript expressions, we can substitute a lot more than variable names. For example, below we can use expression interpolation to embed for some readable inline math:

 
var a = 10;
var b = 10;
console.log(`JavaScript first appeared ${a+b} years ago. Crazy!`); //=> JavaScript first appeared 20 years ago. Crazy! console.log(`The number of JS MVC frameworks is ${2 * (a + b)} and not ${10 * (a + b)}.`);
//=> The number of JS frameworks is 40 and not 200.

They are also very useful for functions inside expressions:

 
function fn() { return "I am a result. Rarr"; }
console.log(`foo ${fn()} bar`);
//=> foo I am a result. Rarr bar.

The ${} works fine with any kind of expression, including member expressions and method calls:

 
var user = {name: 'Caitlin Potter'};
console.log(`Thanks for getting this into V8, ${user.name.toUpperCase()}.`); // => "Thanks for getting this into V8, CAITLIN POTTER"; // And another example
var thing = 'drugs';
console.log(`Say no to ${thing}. Although if you're talking to ${thing} you may already be on ${thing}.`); // => Say no to drugs. Although if you're talking to drugs you may already be on drugs.

If you require backticks inside of your string, it can be escaped using the backslash character \ as follows:

 
var greeting = `\`Yo\` World!`;

Multiline Strings

Multiline strings in JavaScript have required hacky workarounds for some time. Current solutions for them require that strings either exist on a single line or be split into multiline strings using a \ (blackslash) before each newline. For example:

 
var greeting = "Yo \
World";

Whilst this should work fine in most modern JavaScript engines, the behavior itself is still a bit of a hack. One can also use string concatenation to fake multiline support, but this equally leaves something to be desired:

 
var greeting = "Yo " +
"World";

Template Strings significantly simplify multiline strings. Simply include newlines where they are needed and BOOM. Here's an example:

Any whitespace inside of the backtick syntax will also be considered part of the string.

 
console.log(`string text line 1
string text line 2`);

Tagged Templates

So far, we've looked at using Template Strings for string substitution and for creating multiline strings. Another powerful feature they bring is tagged templates. Tagged Templates transform a Template String by placing a function name before the template string. For example:

 
fn`Hello ${you}! You're looking ${adjective} today!`

The semantics of a tagged template string are very different from those of a normal one. In essence, they are a special type of function call: the above "desugars" into

 
fn(["Hello ", "! You're looking ", " today!"], you, adjective);

Note: Nicholas Zakas goes into more detail on the break-down of these arguments in the Template Strings section of his excellent book, Understanding ES6.

Note how the (n + 1)th argument corresponds to the substitution that takes place between the nth and (n + 1)th entries in the string array. This can be useful for all sorts of things, but one of the most straightforward is automatic escaping of any interpolated variables.

For example, you could write a HTML-escaping function such that..

 
html`<p title="${title}">Hello ${you}!</p>`

returns a string with the appropriate variables substituted in, but with all HTML-unsafe characters replaced. Let’s do that. Our HTML-escaping function will take two arguments: a username and a comment. Both may contain HTML unsafe characters (namely ', ", <, >, and &). For example, if the username is "Domenic Denicola" and the comment is "& is a fun tag", we should output:

 
<b>Domenic Denicola says:</b> "&amp; is a fun tag"

Our tagged template solution could thus be written as follows:

 
// 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}"`);
//=> <b>Domenic Denicola says</b>: "&amp; is a fun tag"

Other possible uses include auto-escaping, formatting, localization and in general, more complex substitutions:

 
// Contextual auto-escaping
qsa`.${className}`;
safehtml`<a href="${url}?q=${query}" onclick="alert('${message}')" style="color: ${color}">${message}</a>`; // Localization and formatting
l10n`Hello ${name}; you are visitor number ${visitor}:n! You have ${money}:c in your account!` // Embedded HTML/XML
jsx`<a href="${url}">${text}</a>` // becomes React.DOM.a({ href: url }, text) // DSLs for code execution
var childProcess = sh`ps ax | grep ${pid}`;

Summary

Template Strings are in Chrome 41 beta+, IE Tech Preview, Firefox 35+ and io.js. Practically speaking if you would like to use them in production today, they're supported in major ES6 Transpilers, including Traceur and 6to5. Check out our Template Strings sample over on the Chrome samples repo if you'd like to try them out. You may also be interested in ES6 Equivalents in ES5, which demonstrates how to achieve some of the sugaring Template Strings bring using ES5 today.

Template Strings bring many important capabilities to JavaScript. These include better ways to do string & expression interpolation, multiline strings and the ability to create your own DSLs.

One of the most significant features they bring are tagged templates - a critical feature for authoring such DSLs. They receive the parts of a Template String as arguments and you can then decide how to use the strings and substitutions to determine the final output of your string.

ES6 Template Strings(转)的更多相关文章

  1. ES6 Features系列:Template Strings & Tagged Template Strings

    1. Brief ES6(ECMAScript 6th edition)于2015年7月份发布,虽然各大浏览器仍未全面支持ES6,但我们可以在后端通过Node.js 0.12和io.js,而前端则通过 ...

  2. ES6 & tagged-template-literals & template strings

    ES6 & tagged-template-literals & template strings tagged template https://developer.mozilla. ...

  3. ES6 Template String 模板字符串

    模板字符串(Template String)是增强版的字符串,用反引号(`)标识,它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量. 大家可以先看下面一段代码: $(&quo ...

  4. 用简单的方法学习ES6

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

  5. ES6 Syntax and Feature Overview

    View on GitHub Note: A commonly accepted practice is to use const except in cases of loops and reass ...

  6. 【转】浅谈JavaScript、ES5、ES6

    什么是JavaScript JavaScript一种动态类型.弱类型.基于原型的客户端脚本语言,用来给HTML网页增加动态功能.(好吧,概念什么最讨厌了) 动态: 在运行时确定数据类型.变量使用之前不 ...

  7. io.js入门(三)—— 所支持的ES6(下)

    (接上篇) 标准ES6特性 6. 新的String方法/New String methods 7. 符号/Symbols 8. 字符串模板/Template strings 新的String方法/Ne ...

  8. io.js入门(二)—— 所支持的ES6(上)

    io.js的官网上有专门介绍其所支持的ES6特性的页面(点我查看),上面介绍到,相比nodeJS,io.js已从根本上支持了新版V8引擎上所支持的ES6特性,无需再添加任何运行时标志(如 --harm ...

  9. javascript的replace+正则 实现ES6的字符串模版

    采用拼接字符串的形式,将 JSON 数据嵌入 HTML 中.开始时代码量较少,暂时还可以接受.但当页面结构复杂起来后,其弱点开始变得无法忍受起来: 书写不连贯.每写一个变量就要断一下,插入一个 + 和 ...

随机推荐

  1. 从零开始mycat实验环境搭建

    版本说明 本机: jdk 8 使用IntelliJ IDEA调试MyCAT 1.6 release 主机一:droplet  CentOS 7.5 x86_64 MyCAT 1.6 release O ...

  2. Python第5天

    今日学习的主要内容: 数据类型和变量的总结:(可变:列表,字典)(不可变:字符串,数字,元组) 引出集合概念:不同元素,无序,不可变类型 set方法—>集合 add添加:clear清空:pop删 ...

  3. Centos7的防火墙关闭

    第一步.centos7安装service 第二步. 或者可以不用service,有另一个办法.

  4. 新装 Win7 系统装完驱动精灵,一打开到检测界面就卡死——原因与解决方案

    1.现象: 重装系统后,鼠标反应慢,且不能上网.因此装了个驱动精灵,准备更新下驱动,但驱动精灵一打开到检测界面就卡死(换驱动人生.鲁大师也一样). 2.原因: Win7 系统 iso 中自带的驱动程序 ...

  5. java学习-- String

    String 类的实例是不可改变的,所以你一旦创建了 String 对象,那它的值就无法改变了 String 类是不可改变的解析,例如: String s = "Google"; ...

  6. Android 7.0 通过FileProvider共享文件

    一.概述 Android 7.0后,提供了很多新特性,其中最主要的是禁止了通过file://URI直接在文件操作共享文件(该操作会触发FileUriExposedException),而是通过cont ...

  7. Cmake实践(Cmake Practice)第一部分

    参考资料地址:https://github.com/Akagi201/learning-cmake/blob/master/docs/cmake-practice.pdf 一.初识cmake 1. C ...

  8. 深入理解BERT Transformer ,不仅仅是注意力机制

    来源商业新知网,原标题:深入理解BERT Transformer ,不仅仅是注意力机制 BERT是google最近提出的一个自然语言处理模型,它在许多任务 检测上表现非常好. 如:问答.自然语言推断和 ...

  9. CSS 图像高级 径向渐变

    径向渐变 径向渐变使用 radial-gradient 函数语法. 这个语法和线性渐变很类似, 可以指定渐变结束时的形状 以及它的大小. 默认来说,结束形状是一个椭圆形并且和容器的大小比例保持一致. ...

  10. 小乌龟 coding 克隆、提交一直提示无权限

    因为之前设置过账号,但是网上各种命令行清除都没有用,进入小乌龟设置删除全局配置,系统配置,保存就可以克隆等操作了