javascript / intermediate
Snippet
Tagged Template Literals
Tagged templates allow you to parse template literals with a function. The first argument is an array of string literals, and the remaining arguments are the evaluated expressions.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
function highlight(strings, ...values) {return strings.reduce((acc, str, i) => {const val = values[i] ? `[${values[i]}]` : '';return acc + str + val;}, '');}const author = 'Maria';const action = 'escaped';const message = highlight`${author} has ${action}!`;console.log(message); // [Maria] has [escaped]!
Breakdown
1
function highlight(strings, ...values) { ... }
The 'tag' function that processes the string parts and interpolated values.
2
highlight`${author}...`
Invoking the tag function without parentheses by prefixing the template literal.