Tagged Template Literals With ES6 / ES2015

We briefly covered template literals, but they have an extra feature that we didn’t discuss: tags. You can tag your template literals with a function that will be called and can act as a kind of preprocessor on the content of the template literal.

Here’s a typical example of a template literal:

let name = 'Benedict';
let occupation = 'being awesome';

let sentence = `Hi! I'm ${ name } and I'm busy at ${ occupation }.`;

console.log(sentence);
// Hi! I'm Benedict and I'm busy at being awesome.

Now let’s tag the literal with a useless function:

function useless(strings, ...values) {
  return 'I render everything useless.';
}

let name = 'Benedict';
let occupation = 'being awesome';

let sentence = useless`Hi! I'm ${ name } and I'm busy at ${ occupation }.`;

console.log(sentence);
// I render everything useless.

Obviously the above doesn’t have any use, but where it starts to have more power is when we make use of the strings and values to construct the template literal with some processing.

With our current example:

  • strings is an array with 3 values: Hi! I’m , and I’m busy at and .
  • values is an array with the 2 interpolated values for the name and occupation variables. These values are passed as extra parameters to the tagged function, but here we make use of rest parameters to gather all the extra parameters into a values array.

There always is one more strings value then there are interpolated values. With our example, if there was not period at the end of then sentence, an empty string would be the last value for the strings array, to satisfy the fact that there needs to be one more string value.

Armed with that knowledge, we can therefore create a tag function for the string literal that actually does something:

function uppercase(strings, ...values) {
  let newStr = '';

  for (let i = 0; i < strings.length; i++) {
    if (i > 0) {
      newStr += values[i-1].toUpperCase();
    }
    newStr += strings[i];
  }

  return newStr;
}

let name = 'Benedict';
let occupation = 'being awesome';

let sentence = uppercase`Hi! I'm ${ name } and I'm busy at ${ occupation }.`;

console.log(sentence);
// Hi! I'm BENEDICT and I'm busy at BEING AWESOME.
  Tweet It
✖ Clear

🕵 Search Results

🔎 Searching...