How can I do String interpolation in JavaScript?

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.


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.


let str = `Name is "Programming Basic"`


Name is "Programming Basic"

String Interpolation with Variable Substitutions

Template Literals allows us to add variables in a String.


let firstName = "Max"
let lastName = "Payne"
let fullName = `My Name is ${firstName} ${lastName}`


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.


let a = 10;
let b = 10;
let total = `The sum of ${a} and ${b} is ${a+b} `;


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.


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


Message: Hello World !!

Related Topics:

How To Create Multiline String In JavaScript?

Truncate A String In JavaScript With Example

Combine Multiple Strings Into A Single String | Concatenate Strings

JavaScript - String Replace All Appearances

Remove Whitespace From JavaScript String

How to compare two strings in JavaScript?