Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1032608 of Template literals

  • Revision slug: Web/JavaScript/Reference/Template_literals
  • Revision title: Template literals
  • Revision id: 1032608
  • Created:
  • Creator: panhezeng
  • Is current revision? No
  • Comment

Revision Content

{{JsSidebar("More")}}

Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 / ES6 specification.

Syntax

`string text`

`string text line 1
 string text line 2`

`string text ${expression} string text`

tag `string text ${expression} string text`

Description

Template literals are enclosed by the back-tick (` `) (grave accent) character instead of double or single quotes. Template literals can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}). The expressions in the place holders and the text between them get passed to a function. The default function just concatenates the parts into a single string. If there is an expression preceding the template literal (tag here),  the template string is called "tagged template literal". In that case, the tag expression (usually a function) gets called with the processed template literal, which you can then manipulate before outputting.

Multi-line strings

Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings:

console.log("string text line 1\n"+
"string text line 2");
// "string text line 1
// string text line 2"

To get the same effect with multi-line strings, you can now write:

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

Expression interpolation

In order to embed expressions within normal strings, you would use the following syntax:

var a = 5;
var b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."

Now, with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."

Tagged template literals

A more advanced form of template literals are tagged template literals. With them you are able to modify the output of template literals using a function. The first argument contains an array of string literals ("Hello " and " world" in this example). The second, and each argument after the first one, are the values of the processed (or sometimes called cooked) substitution expressions ("15" and "50" here). In the end, your function returns your manipulated string. There is nothing special about the name tag in the following example. The function name may be anything you want.

var a = 5;
var b = 10;

function tag(strings, ...values) {
  console.log(strings[0]); // "Hello "
  console.log(strings[1]); // " world "
  console.log(values[0]);  // 15
  console.log(values[1]);  // 50

  return "Bazinga!";
}

tag`Hello ${ a + b } world ${ a * b }`;
// "Bazinga!"

Tag functions need not return a string, as shown in the following example.

function template(strings, ...keys) {
  return (function(...values) {
    var dict = values[values.length - 1] || {};
    var result = [strings[0]];
    keys.forEach(function(key, i) {
      var value = Number.isInteger(key) ? values[key] : dict[key];
      result.push(value, strings[i + 1]);
    });
    return result.join('');
  });
}

var t1Closure = template`${0}${1}${0}!`;
t1Closure('Y', 'A');  // "YAY!" 
var t2Closure = template`${0} ${'foo'}!`;
t2Closure('Hello', {foo: 'World'});  // "Hello World!"

Raw strings

The special raw property, available on the first function argument of tagged template literals, allows you to access the raw strings as they were entered.

function tag(strings, ...values) {
  console.log(strings.raw[0]); 
  // "string text line 1 \\n string text line 2"
}

tag`string text line 1 \n string text line 2`;

In addition, the {{jsxref("String.raw()")}} method exists to create raw strings just like the default template function and string concatenation would create.

String.raw`Hi\n${2+3}!`;
// "Hi\n5!"

Specifications

Specification Status Comment
{{SpecName('ES6', '#sec-template-literals', 'Template Literals')}} {{Spec2('ES6')}} Initial definition. Defined in several section of the specification: Template Literals, Tagged Templates
{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}} {{Spec2('ESDraft')}} Defined in several section of the specification: Template Literals, Tagged Templates

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Edge Firefox (Gecko) Internet Explorer Opera Safari
Basic support {{CompatChrome(41)}} {{CompatVersionUnknown}} {{CompatGeckoDesktop("34")}} {{CompatNo}} {{CompatOpera(28)}} {{CompatSafari(9)}}
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support {{CompatNo}} {{CompatChrome(41)}} {{CompatGeckoMobile("34")}} {{CompatNo}} {{CompatOpera(28)}} {{CompatSafari(9)}}

See also

Revision Source

<div>{{JsSidebar("More")}}</div>

<p>Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them. They were called "template strings" in prior editions of the ES2015 / ES6 specification.</p>

<h2 id="Syntax">Syntax</h2>

<pre class="syntaxbox">
`string text`

`string text line 1
 string text line 2`

`string text ${expression} string text`

tag `string text ${expression} string text`
</pre>

<h2 id="Description">Description</h2>

<p>Template literals are enclosed by the back-tick (` `) (<a href="https://en.wikipedia.org/wiki/Grave_accent">grave accent</a>) character instead of double or single quotes. Template literals can contain place holders. These are indicated by the Dollar sign and curly braces (<code>${expression}</code>). The expressions in the place holders and the text between them get passed to a function. The default function just concatenates the parts into a single string. If there is an expression preceding the template literal (<code>tag</code> here),&nbsp; the template string is called "tagged template literal". In that case, the tag expression (usually a function) gets called with the processed template literal, which you can then manipulate before outputting.</p>

<h3 id="Multi-line_strings">Multi-line strings</h3>

<p>Any new line characters inserted in the source are part of the template literal. Using normal strings, you would have to use the following syntax in order to get multi-line strings:</p>

<pre class="brush: js">
console.log("string text line 1\n"+
"string text line 2");
// "string text line 1
// string text line 2"</pre>

<p>To get the same effect with multi-line strings, you can now write:</p>

<pre class="brush: js">
console.log(`string text line 1
string text line 2`);
// "string text line 1
// string text line 2"</pre>

<h3 id="Expression_interpolation">Expression interpolation</h3>

<p>In order to embed expressions within normal strings, you would use the following syntax:</p>

<pre class="brush: js">
var a = 5;
var b = 10;
console.log("Fifteen is " + (a + b) + " and\nnot " + (2 * a + b) + ".");
// "Fifteen is 15 and
// not 20."</pre>

<p>Now, with template literals, you are able to make use of the syntactic sugar making substitutions like this more readable:</p>

<pre class="brush: js">
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and\nnot ${2 * a + b}.`);
// "Fifteen is 15 and
// not 20."</pre>

<h3 id="Tagged_template_literals">Tagged template literals</h3>

<p>A more advanced form of template literals are <em>tagged</em> template literals. With them you are able to modify the output of template literals using a function. The first argument contains an array of string literals ("Hello " and " world" in this example). The second, and each argument after the first one, are the values of the processed (or sometimes called <em>cooked</em>) substitution expressions ("15" and "50" here). In the end, your function returns your manipulated string. There is nothing special about the name tag in the following example. The function name may be anything you want.</p>

<pre class="brush: js">
var a = 5;
var b = 10;

function tag(strings, ...values) {
  console.log(strings[0]); // "Hello "
  console.log(strings[1]); // " world "
  console.log(values[0]);  // 15
  console.log(values[1]);  // 50

  return "Bazinga!";
}

tag`Hello ${ a + b } world ${ a * b }`;
// "Bazinga!"
</pre>

<p>Tag functions need not return a string, as shown in the following example.</p>

<pre class="brush: js">
function template(strings, ...keys) {
  return (function(...values) {
    var dict = values[values.length - 1] || {};
    var result = [strings[0]];
    keys.forEach(function(key, i) {
      var value = Number.isInteger(key) ? values[key] : dict[key];
      result.push(value, strings[i + 1]);
    });
    return result.join('');
  });
}

var t1Closure = template`${0}${1}${0}!`;
t1Closure('Y', 'A');  // "YAY!" 
var t2Closure = template`${0} ${'foo'}!`;
t2Closure('Hello', {foo: 'World'});  // "Hello World!"
</pre>

<h3 id="Raw_strings">Raw strings</h3>

<p>The special <code>raw</code> property, available on the first function argument of tagged template literals, allows you to access the raw strings as they were entered.</p>

<pre class="brush: js">
function tag(strings, ...values) {
  console.log(strings.raw[0]); 
&nbsp; // "string text line 1 \\n string text line 2"
}

tag`string text line 1 \n string text line 2`;
</pre>

<p>In addition, the {{jsxref("String.raw()")}} method exists to create raw strings just like the default template function and string concatenation would create.</p>

<pre class="brush: js">
String.raw`Hi\n${2+3}!`;
// "Hi\n5!"</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('ES6', '#sec-template-literals', 'Template Literals')}}</td>
   <td>{{Spec2('ES6')}}</td>
   <td>Initial definition. Defined in several section of the specification: <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-template-literals">Template Literals</a>, <a href="https://www.ecma-international.org/ecma-262/6.0/#sec-tagged-templates">Tagged Templates</a></td>
  </tr>
  <tr>
   <td>{{SpecName('ESDraft', '#sec-template-literals', 'Template Literals')}}</td>
   <td>{{Spec2('ESDraft')}}</td>
   <td>Defined in several section of the specification: <a href="https://tc39.github.io/ecma262/#sec-template-literals">Template Literals</a>, <a href="https://tc39.github.io/ecma262/#sec-tagged-templates">Tagged Templates</a></td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Edge</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatChrome(41)}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoDesktop("34")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatOpera(28)}}</td>
   <td>{{CompatSafari(9)}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatChrome(41)}}</td>
   <td>{{CompatGeckoMobile("34")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatOpera(28)}}</td>
   <td>{{CompatSafari(9)}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="See_also">See also</h2>

<ul>
 <li>{{jsxref("String")}}</li>
 <li>{{jsxref("String.raw()")}}</li>
 <li><a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar">Lexical grammar</a></li>
 <li><a href="https://gist.github.com/WebReflection/8f227532143e63649804">Template-like strings in ES3 compatible syntax</a></li>
 <li><a href="https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/">"ES6 in Depth: Template strings" on hacks.mozilla.org</a></li>
</ul>
Revert to this revision