J

JavaScript Handbook

Clean • Professional

String Templates

1 minute

String Template

String templates (introduced in ES6) provide a modern, flexible way to work with strings in JavaScript. They allow multi-line strings, variable interpolation, and easy HTML generation using backticks (`).

Backticks Syntax

String templates are defined using **backticks ()** instead of single (') or double quotes ("`). This enables enhanced functionality like interpolation and multi-line strings.

let text = `Hello World!`;
console.log(text); // Output: Hello World!

Quotes Inside Strings

You can include single (') and double quotes (") directly within template literals without escaping them.

let text = `He's often called "Johnny"`;
console.log(text); // Output: He's often called "Johnny"

Multi-line Strings

String templates allow multi-line strings without using \\n or concatenation, improving readability.

let text = `
The quick
brown fox
jumps over
the lazy dog`;
console.log(text);
/* Output:
The quick
brown fox
jumps over
the lazy dog
*/

Interpolation

String templates support variable and expression substitution using ${}.

Variable Substitution

let firstName = "John";
let lastName = "Doe";
let text = `Welcome ${firstName}, ${lastName}!`;
console.log(text); // Output: Welcome John, Doe!

Expression Substitution

You can include JavaScript expressions, like calculations or function calls, inside ${}:

let price = 10;
let VAT = 0.25;
let total = `Total: ${(price * (1 + VAT)).toFixed(2)}`;
console.log(total); // Output: Total: 12.50

HTML Templates

String templates are particularly useful for generating HTML markup, allowing clean integration of variables and multi-line formatting.

let header = "String Templates";
let tags = ["template strings", "javascript", "es6"];
let html = `<h2>${header}</h2><ul>`;
for (const x of tags) {
  html += `<li>${x}</li>`;
}
html += `</ul>`;
console.log(html);
/* Output:
<h2>String Templates</h2><ul><li>template strings</li><li>javascript</li><li>es6</li></ul>
*/

 

Article 0 of 0