Template strings in JavaScript consist of literal text, and placeholders where the runtime can evaluate an expression to inject data into the text.

Why template strings?

Before we delve into template strings, let's identify the capabilities of some languages like Ruby and Python that are lacking in JavaScript.

  • String formatting
  • String tagging for safe HTML escaping & localization
  • Multiple strings without hacks
  • Embedded expressions
  • String interpolation

Template strings work more like a function call than a mechanism for defining templates.


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

var message = `Hello!`;

Backtick characters (`) enclose the entire template literal, while $ and {} denote the substitutions. Inside a substitution, you can use identifiers and expressions.

String Substitution

String substitution allows us to take any valid JavaScript expression and inside a Template Literal, the result will be output as part of the same string.

var name = 'Sean';
var message = `Hello ${name}!`;

console.log(message); // Hello Sean!

You are not limited to variables, you can use functions inside an expression:

var dateOfBirth = 1985;
var message = `My age is ${2015 - dateOfBirth}`;

console.log(message); // My age is 30

Multiline Strings

Multiline strings in JavaScript has been achieved so far by adding a backslash (****) character before each newline.

var message = "This is a \
              multi-line message";

Template strings can span multiple lines:

var message = `This is a
              multi-line message`;

Multiline literals will contain a newline character in template strings.

Tagged Templates

Tagged Templates transform a Template String by placing a function name before the template string.

var name = 'Sean';
var dateOfBirth = 1985;

fn`Hello ${name}! You are ${2015 - dateOfBirth} today`;

Tagged template strings are a special type of a function call. The above string will be converted into:

var name = 'Sean';
var dateOfBirth = 1985;

fn(["Hello ", "! You are ", " today"], name, dateOfBirth);

Safe HTML escaping

You could write a HTML-escaping function as follows:

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

This returns a string with the appropriate variables substituted in, but with all HTML-unsafe characters replaced.