How can I do String interpolation in JavaScript?

In this article, we will learn different ways on how to do string interpolation in JavaScript using template literals.

String Interpolation means to replace or insert variables and expressions into a string. This can be done easily in ES6 using Template Literals.

Template Literals use back-ticks (` `) instead of the quotes (” “) to define a string.

Example:

let str = `Hello I am a String`

Using Quotes inside String

Using Template literals, both single and double quotes can be use inside a string.

Example:

let str = `Name is "Programming Basic"`
console.log(str)

Output:

Name is "Programming Basic"

String Interpolation with Variable Substitutions

Template Literals allows us to add variables in a String.

Example:

let firstName = "Max"
let lastName = "Payne"
let fullName = `My Name is ${firstName} ${lastName}`
console.log(fullName)

Output:

My Name is Max Payne

Expression Substitution using Template Literals

In JavaScript, string interpolation allow us to embed an expression into the string. With template literals we can add value values and do mathematical calculations inside a string.

Example:

let a = 10;
let b = 10;
let total = `The sum of ${a} and ${b} is ${a+b} `;
console.log(total)

Output:

The sum of 10 and 10 is 20 

String Interpolation with Function Expression

Using Template Literals we can also interpolate a function into a string in JavaScript.

Example:

function hello() { 
    return "Hello World"; 
}
console.log(`Message: ${hello()} !!`);

Output:

Message: Hello World !!

Related Topics:

How To Create Multiline String In JavaScript?

Combine Multiple Strings Into A Single String | Concatenate Strings

JavaScript – String Replace All Appearances

How to compare two strings in JavaScript?

JavaScript – How to Remove Character From A String.

Javascript – Convert array to String (with and without commas)

Capitalize First Letter of a String – JavaScript

Scroll to Top