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 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"
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
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
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?
Truncate A String In JavaScript With Example
Combine Multiple Strings Into A Single String | Concatenate Strings
JavaScript - String Replace All Appearances