JS: Template String

By Xah Lee. Date: . Last updated: .

What is Template String

New in JS2015.

String can be created by bracketing text with `U+60: GRAVE ACCENT`. This this called template string.

console.log(`my cat` === "my cat")

Literal Line Break Allowed

Literal newline character is allowed:

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

console.log( x ===  "aa\nbb" );

Embeded Expression

Any expression in the form ${expr} is evaluated and result inserted into the string.

// template string example
console.log(`2 + 3 = ${2 + 3}` === `2 + 3 = 5`);

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

Here is a example with embedded variable:

// variable substitution inside template string
let x = 76;
console.log(`${x} dollars` === `76 dollars`);

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

Escape GRAVE ACCENT

If you want to include a GRAVE ACCENT in a template string, add a backslash in front, like this \`.

/* escape grave mark in template string */
console.log(`a\`b` === "a`b");

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

/* escape the expression part in template string */
let x = 2;
console.log(`${x}` === "2");
console.log(`\${x}` === "${x}");
console.log(`$\{x}` === "${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

JavaScript, String

BUY Ξ£JS JavaScript in Depth