JS: Template String

By Xah Lee. Date: . Last updated: .

New in ES2015.

String can be enclosed by the character ` (U+60: GRAVE ACCENT) , like this:

console.log(`How are you?`);

When string is enclosed by GRAVE ACCENT, any ${…} inside will be evaluated and result inserted into the string.

// template string example
    `two plus three is ${2+3}`
); // two plus three is 5

Template string allows you to easily create “templates” by embedding expressions. This programing language feature is sometimes known as interpolation, in Perl, Ruby, PHP.

The ${…} is called place-holder, or substitution string.

Here's a example with embedded variable:

// variable interpolation inside template string

let x = 76;

    `You have ${x} points.`
); // You have 76 points.

Literal newline character is allowed:

// template string allow literal newline
let x = `aa

// prints in 2 lines

Escape Characters

If you want to include a ` in a template string, you can escape it by backslash, like this \`.

// escape grave mark in template string
); // prints a`b

You can also escape ${…} by \${…} or $\{…}.

// escape the expression part in template string

let x = 2;

console.log(`${x}`); // prints 2

console.log(`\${x}`); // prints ${x}

console.log(`$\{x}`); // prints ${x}

When the expression is a object, its .toString() method is used to convert it to string. (or, with inheritance up to Object.toString()) [see JS: Prototype and Inheritance]

Nest Template String

Template string can be nested.

// nested template string

let x = "B";

    `wow ${`A${x}C`}`
); // wow ABC

Tagged Template String

[see JS: Tagged Template String]


ECMAScript 2015 §ECMAScript Language: Lexical Grammar#sec-template-literal-lexical-components

ECMAScript 2015 §ECMAScript Language: Expressions#sec-template-literals

String Topic

  1. JS: Source Code Encoding
  2. JS: String Code Unit vs Code Point
  3. JS: Unicode Character Escape Sequence
  4. JS: Allowed Characters in Identifier
  5. HTML: Allowed Characters in id Attribute
  6. HTML: Character Sets and Encoding
  7. HTML/XML Entity List

  1. JS: Template String
  2. JS: Convert String to Number
  3. JS: Encode URL, Escape String
  4. JS: Format Number
  5. JS: JSON

  1. JS: String Object
  2. JS: String.prototype
  3. JS: String Constructor
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon