javascript – js Variable substitution in a string

Question:

Accidentally stumbled upon a construct for inserting variables into a string:

var name = "World";
console.log(`Hello ${name}!`); // выведет "Hello World!"

What is the feature and how long has it been around? Always used concatenation or replace/replaceObject if necessary…

console.log('Hello ' + name + '!');
console.log('Hello {name}!'.replace('{name}', name));
console.log('Hello {name}!'.replaceObject({'name': name});

Answer:

Template strings (templates) are string literals that allow expressions. You can use multiline literals and interpolation capabilities.

var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b} and not ${2 * a + b}.`);
// "Fifteen is 15 and not 20."

Documentation .

Scroll to Top