Computer >> Computer tutorials >  >> Programming >> Javascript

How to do string interpolation in JavaScript?


JavaScript since ES6 has template string support which gives native support for string interpolation. These are called template literals. Template literals are string literals that allow embedded expressions. Template strings use back-ticks (``) rather than the single or double-quotes. A template string could thus be written as −

var greeting = `Hello World!`;

Template strings can use placeholders for string substitution using the ${ } syntax.

Example 1

var name = "Brendan";
console.log('Hello, ${name}!');

Output

This will give the following output −

Hello, Brendan!

Example 2

Template literals and expressions

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

Output

This will give the following output −

The sum of 10 and 10 is 20

Example 3

Template literals and function expression

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

Output

This will give the following output −

Message: Hello World !!

Template strings can contain multiple lines.

Example

var multiLine = `
   This is
   a string
   with multiple
   lines`;
console.log(multiLine)

Output

This will give the following output −

This is
a string
with multiple
line