JavaScript: 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
console.log(
    `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

var x = 76;

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

Literal newline character is allowed:

// template string allow literal newline
var x = `aa
bb`;

console.log(x);
// 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
console.log(
    `a\`b`
); // prints a`b

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

// escape the expression part in template string

var 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 JavaScript: Prototype and Inheritance

Nest Template String

Template string can be nested.

// nested template string

var x = "B";

console.log(
    `wow ${`A${x}C`}`
); // wow ABC

Tagged Template String

〔►see JavaScript: Tagged Template String

Reference

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

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

String Topic

  1. JavaScript: Default Charset/Encoding
  2. JavaScript: String is 16-Bit Unit Sequence
  3. JavaScript: Unicode Character Escape Sequence
  4. JavaScript: Allowed Characters in Identifier
  5. HTML: Allowed Characters in id Attribute
  6. HTML: Character Sets and Encoding
  7. HTML XML Entities

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

  1. JavaScript: String Object
  2. JavaScript: String.prototype
  3. JavaScript: String Constructor
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.