JavaScript String Templates

Synonyms:

  • Template Literals
  • Template Strings
  • String Templates
  • Back-Ticks Syntax

Back-Ticks Syntax

Template LiteralsUse backticks (`) instead of quotes ("`) to define strings:

Example

let text = `Hello World!`;

Try It Yourself

Quotation marks within strings

By usingTemplate LiteralsYou can use both single and double quotes in the string at the same time:

Example

let text = `He's often called "Johnny"`;

Try It Yourself

Multiline Strings

Template LiteralsMultiline strings are allowed:

Example

let text =
The quick
brown fox
jumps over
the lazy dog`;

Try It Yourself

Interpolation

Template LiteralsIt provides a simple way to insert variables and expressions into strings.

This method is called string interpolation (string interpolation).

Syntax

${...}

Variable Replacement

Template LiteralsVariables are allowed within strings:

Example

let firstName = "Bill";
let lastName = "Gates";
let text = `Welcome ${firstName}, ${lastName}!`;

Try It Yourself

Using real values to automatically replace variables is calledString Interpolation.

Expression Replacement

Template LiteralsExpressions are allowed within strings:

Example

let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;

Try It Yourself

Using real values to automatically replace expressions in strings is called string interpolation.

HTML Template

Example

let header = "Templates Literals";
let tags = ["template literals", "javascript", "es6"];
let html = `<h2>${header}</h2><ul>`;
for (const x of tags) {
  html += `<li>${x}</li>`;
}
html += `</ul>`;

Try It Yourself

Browser Support

Internet Explorer does not supportTemplate Literals.

The first browser version to fully support template literals is:

Chrome IE Firefox Safari Opera
Chrome 41 Edge 13 Firefox 34 Safari 10 Opera 29
March 2015 November 2015 December 2014 September 2016 April 2015

Complete String Reference

For a complete reference, please visit our full JavaScript String Reference Manual.

This manual includes descriptions and examples of all string properties and methods.