How can I do String interpolation in JavaScript?

featured Image

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

Related Posts

featured Image

Get the 10 characters from a string using JavaScript.

Here, in this article we will learn how to get the first 10 character from any string using JavaScript. Here we will be using JavaScript’s String method substring. What is…

Read more
featured Image

Convert date to long date format using JavaScript

In this article we will look into how to convert a date to a long date format using JavaScript. To convert it to a long format we will be using…

Read more
featured Image

Prevent body from scrolling when a modal is opened

Here, in this article, we will learn how to prevent the body from scrolling when a modal or a pop-up is opened using JavaScript. The scroll event is not cancelable….

Read more