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:

`How are you?`

console.log(`my cat` === "my cat"); // true

Literal Line Break Allowed

Literal newline character is allowed:

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

console.log(x);
// prints in 2 lines

Embeded Expression

Any form ${expr} in tempate string will have the expr evaluated and result inserted into the string.

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

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

Here's a example with embedded variable:

// variable interpolation inside template string

let x = 76;

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

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]

Escape Characters

If you want to include a GRAVE ACCENT 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

let x = 2;

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

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

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

Nest Template String

Template string can be nested.

// nested template string

let x = "B";

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

Tagged Template String

[see JS: Tagged Template String]

Reference

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

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

JS String

  1. String Overview
  2. Template String
  3. Char, Code Unit, Code Point
  4. String Escape Sequence
  5. Unicode Escape Sequence
  6. String to Number
  7. Encode URL, Escape String
  8. Format Number
  9. Source Code Encoding
  10. Allowed Characters in Identifier
  11. String Object
  12. String.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Reference
  5. DOM
  6. SVG
  7. Web Dev Blog