xxxxxxxxxx
//Must use backticks, `, in order to work.
let a = 5;
let b = 10;
console.log(`Fifteen is ${a + b} and
not ${2 * a + b}.`);
//Output:
//Fifteen is 15 and not 20.
xxxxxxxxxx
//Regular string
var rgb = "rgb(" + r + "," + g + "," + b + ")";
//Template literal
var rgb = `rgb(${r}, ${g}, ${b})`;
xxxxxxxxxx
<!DOCTYPE html>
<title> JavaScript Template Literals </title>
<script type="text/javascript">
let users = [{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz"
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna@melissa.tv"
},
{
"id": 3,
"name": "Clementine Bauch",
"username": "Samantha",
"email": "Nathan@yesenia.net"
}
]
<!-- JavaScript Template Literals in action -->
let html_markup = `<table>
${users.map(user => `<tr>
<td>${user.name}</td>
<td>${user.email}</td>
</tr>`).join('')}
</table>`;
document.body.innerHTML = html_markup
</script>
xxxxxxxxxx
// TEMPLATE LITERALS example
console.log(`Hi, I'm ${p.name}! Call me "${p.nn}".`);
xxxxxxxxxx
// Template Literals in javascript
// Longhand:
let firstName = "Chetan", lastName = "Nada";
const welcome = 'Hello my name is ' + firstName + ' ' + lastName;
console.log(welcome); //Hello my name is Chetan Nada
// Shorthand:
const welcome_ = `Hello my name is ${firstName} ${lastName}`;
console.log(welcome_); //Hello my name is Chetan Nada
xxxxxxxxxx
let fruits = {
banana: 1,
orange: 5
};
let sentence = `We have ${banana} Banana/s and ${orange} orange/s!`;
console.log(sentence); // We have 1 Banana/s and 5 orange/s!
xxxxxxxxxx
const first_name = "Jack";
const last_name = "Sparrow";
console.log('Hello ' + first_name + ' ' + last_name);
xxxxxxxxxx
var str = 'Release date: ' + date // ES5
let str = `Release Date: ${date}` // ES6
xxxxxxxxxx
// Template literal example
const name = 'Alice';
const greeting = `Hello ${name}!`;
console.log(greeting);
xxxxxxxxxx
var str = "foo";
var myString = `Insert variables inside strings like this: ${str}`;