Last active
November 12, 2017 20:11
-
-
Save aderaaij/7fbd85c6b602bbc3619b9c085c5b859f to your computer and use it in GitHub Desktop.
With tagged templates we can modify a template string with a function tagged in front of it. str += `${string} <span class='hl'>${values[i] || ''}</span>`;
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* The highlight function we tagged on to our template string | |
Arguments: An array of strings in between variables and the variables | |
We could use `strings, age, name` as arguments but using the spread operator | |
to get all the variables is better scalable. */ | |
function highlight(strings, ...values) { | |
let str = ''; | |
/* For each string we add both string and value to the let value. If value doesn't exist, | |
add empty string. */ | |
strings.forEach((string, i) => { | |
str += `${string} <span class='hl'>${values[i] || ''}</span>`; | |
}); | |
return str; | |
} | |
const name = 'Snickers'; | |
const age = 100; | |
const gender = 'male' | |
// Tag the 'highlight' function to the template string, the template string | |
// acts as arguments for the function | |
const sentence = highlight`My dog's name is ${name} and he is ${age} years old and he's a ${gender}`; | |
document.body.innerHTML = sentence; | |
console.log(sentence); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment