Explain Codes LogoExplain Codes Logo

How can I do string interpolation in JavaScript?

javascript
template-literals
string-interpolation
es6
Anton ShumikhinbyAnton Shumikhin·Jan 16, 2025
TLDR

Use template literals in JavaScript for string interpolation. Wrap your text with back-ticks (` `) and include variables or expressions inside ${ ... }.

const name = 'Alice'; console.log(`Hello there, ${name}!`); // "Hello there, Alice!"

It's like slipping a secret note inside an invitation. Suddenly, your strings have a life of their own!

Getting to know your template literals

ES6 template literals, introduced in ECMAScript 2015 (ES6), provide a significant upgrade for handling strings over concatenation. You declare them with backticks (`), allowing multiline strings and even so-called "tagged" template literals for custom parsing.

Eloquent multilines

Crafting multiline strings with old-school concatenation feels like threading a needle with spaghetti:

var multiLineString = 'Line 1\n' + 'Line 2\n' + 'Line 3'; // feels like building a house with sticky tape!

With template literals? Falling off a log.

const multiLineString = `Line 1 Line 2 Line 3`; // now we're laying bricks with mortar

Tagged template literals

Tag functions turn your template literal into a secret agent, parsing your string through a function for custom string operations:

function highlight(strings, ...values) { return strings.map((str, i) => `${str}<mark>${values[i] || ""}</mark>`).join(''); } const name = 'Alice'; const greeting = highlight`Hello, ${name}!`; // Alice pops right out!

It's a matter of style

Template literals compared to traditional string concatenation is like comparing apples and... well, rotten apples:

  • Brevity: The soul of wit and healthy code.
  • Readability: It's like an open book, easy-peasy.
  • Maintenance: Shaves off those pesky syntax errors. Goodbye misplaced +!

Sneaky tactics for string interpolation

ES6 Template literals are great, but sometimes, you need a pinch of creativity for dynamic expressions at runtime (they're always fashionably late!).

The cunning supplant function and the .replace() method

Pre-template literals? Douglas Crockford, the Indiana Jones of JavaScript, journeyed deep into uncharted terrains, returning with the supplant function:

String.prototype.supplant = function (o) { return this.replace(/{([^{}]*)}/g, function (a, b) { var r = o[b]; return typeof r === 'string' || typeof r === 'number' ? r : a; }); }; var template = "Hello, {name}!"; var result = template.supplant({ name: "Alice" }); // "Hello, Alice!" Clever as a box of foxes!

The .replace() method can also perform multi-variable replacement:

const template = "Hello, {{name}}! Age: {{age}}"; const data = { name: "Alice", age: 30 }; Object.keys(data).forEach(key => { template = template.replace(new RegExp(`{{${key}}}`, 'g'), data[key]); }); // Alice isn't just getting older, she's getting better!

DOM templates and jQuery

For frontend developers, HTML templates might be the bee's knees! You can either whip up HTML strings using JavaScript's template literals, or pair it with <template> tags and jQuery for a more rigorous DOM manipulation:

<template id="user-template"> <span>Name: {{name}}</span> <span>Age: {{age}}</span> </template>
const user = { name: 'Alice', age: 30 }; const template = document.getElementById('user-template').innerHTML; const filledTemplate = Object.entries(user).reduce( (acc, [key, value]) => acc.replace(new RegExp(`{{${key}}}`, 'g'), value), template ); $('#user-container').html(filledTemplate); // Alice greets you from the DOM with her age!

Never skip escaping special characters, or else XSS attacks could ruin the party.

Browser compatibility and fallbacks

Before you launch into using template literals, do remember to check your browser compatibility. Older browsers (yes, looking at you, IE*) might need fallbacks or polyfills. You can check the latest compatibility from sources like the Mozilla Developer Network.