How can I do String interpolation in JavaScript?
Article on different ways we can do string interpolation in JavaScript using template literals or string templates.
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
Related Posts
Capitalize First Letter of a String - JavaScript
This article is about how to capitalize the first letter of a string using JavaScript.
Check if String starts with a space in JavaScript
Find out whether a string starts with a space or not using regex test method, string match method and startsWith method in JavaScript.
JavaScript - Detect if a string contains any space
FInd out how to detect if a string contains any white space using regex test() method and string indexOf() method in Javascript.
Split a String into chunks of N character into an array in JavaScript
Find out how to split String into Substrings by length of N characters in JavaScript using split(), match() and substr() methods.
