javascript / intermediate
Snippet
Tagged Template Literals
Tagged templates allow you to process template literals using a custom function. The function receives the static string parts and the dynamic expression results as separate arguments.
snippet.js
1
2
3
4
5
6
function highlight(strings, ...values) {return strings.reduce((acc, str, i) =>`${acc}${str}<mark>${values[i] || ''}</mark>`, '');}const name = 'Gemini';const output = highlight`Hello, ${name}!`;
Breakdown
1
function highlight(strings, ...values) {
A tag function where 'strings' is an array of literals and 'values' contains the interpolated expressions.
2
highlight`Hello, ${name}!`;
Invokes the tag function by placing it directly before the template literal.