JS: Template String
What is template string
(new in ECMAScript 2015)
String can be created by bracketing text with `U+60: GRAVE ACCENT`.
This this called template string.
Use \` to embed a GRAVE ACCENT.
console.log(`my cat`); // my cat /* embed a GRAVE ACCENT */ console.log(`cat \` dog`); // cat ` dog
Literal line break allowed
Literal newline character is allowed:
/* template string allow literal newline */ let x = `aa bb`; console.log(x); // aa // bb
Embed expression
Any expression in the form ${expr} is evaluated and result inserted into the string.
The ${expr} is called place-holder, or substitution string.
// template string example console.log(`2 + 3 = ${2 + 3}`); // 2 + 3 = 5
// 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.
Place-holder as literal text
to have the place-holder as literal text, put a backslash in front of the dollar sign or the opening bracket.
/* escape the expression part in template string */ let x = 2; console.log(`${x}`); // 2 console.log(`\${x}`); // ${x} console.log(`$\{x}`); // ${x}
String escape sequence
Template String supports string escape sequence.
Nest template string
Template string can be nested.
/* nested template string */ let x = "B"; console.log(`wow ${`A${x}C`}`); // wow ABC