Template Literals
Also known as Template Strings or String Literals.
Template literals provide us with an alternative to string concatenation.
Template literals allow us to insert variables into a string.
This uses the Backtick ` to enclose the string characters
var myString1 = "one"
var myString2 = "two"
var myString3 = `text $(myString1) more text $(myString2)`
var myString3 = "text " + myString1 + " more text " + myString2
Whitespace
Template literals preserve white space.
var myString1 = "word2"
var myString4 = ` word1 $(myString1) word3 `
var myString4 = " word1 " + "word2" + " word3 "
Multi-Line
Template literals preserve the line breaks.
var myString3 = `text $(myString1)
more text
$(myString2)`
var myString1 = 100;
var myString4 = `some text $("$" + myString1)`;
Very useful for multi-line strings
Instead of having to use the '\' character at the end
const string = "first part\
second part"
you can now use a back tick character
const string = `first part
second part`
With Expressions
var myString1 = 'one plus one is ${ 1 + 1 }';
let bool1 = true;
let myString2 = 'the opposite of true is ${!bool1}';
© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext