Overriding template literal strings

Overriding template literal strings

Have you been using template literals for a while? Most likely, but did you know that you can override how it constructs the overall string? I didn’t until recently.

If you haven’t seen it, then I think you’ll be sure to think that this code is really cool and so much potential use in other areas.

It’s called tagged templates. It means that rather than calling your literal with the standard joining method, you pass your arguments to your own method.
See the below – as ever code is the best way to explain.

const person1 = "Mike";
const person2 = "Bob";

const taggedTemplateStringLiteral = myMethod`you can say hello to ${person1} and ${person2} :)`;

function myMethod(baseMessages, ...params) {
  // The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in single output value.
  // array.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
  return baseMessages.reduce((acc, cur, i) => {
    acc += `${params[i - 1]?.toUpperCase() ?? ""} ${cur}`;
    return acc;
  });

  /*   Adding in the below as this is perhaps a more common approach,
       but as show in previous post you can improve undefined checks
       with nullish coalescing as shown in the above snippet.

    return baseMessages.reduce((acc, cur, i) => {
      acc += `${params[i - 1] ? params[i - 1].toUpperCase() : ""} ${cur}`;
      return acc;
    }); 
  */
}

What’s going on?

Firstly you have you grave character `. This make it into a template literal. When a string is enclosed with those then each portion (split up by using ${ } for code/var segments) is then included into an array.
Next each parameter, whatever is evaluated for each ${ } block is passed as a separate parameter. You could call them individually or in my case I used the rest (…) operator to grab them all.

myMethod`you can say hello to ${person1} and ${person2} :)`

The means to invoke the method is what caught my eye, in that you do not call it like an actual method! The above ends up being the same as –

myMethod(["you can say hello to ", " and ", " :)"], "Mike", "Bob" );

Which is rather smart and a great little snippet to remember.

Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.