Understanding Tagged Template Literals

marlonry

marlonry

Posted on February 7, 2021

Understanding Tagged Template Literals

With the introduction of Template Literals or Template Strings, string manipulations have been made easier with features such as embedded expressions, multi-line strings as well as raw strings. See some examples below.

const str = `I am a multi-line
String`;
Enter fullscreen mode Exit fullscreen mode
const expression = "expression";
const str = `I am a string with a ${expression}`;
Enter fullscreen mode Exit fullscreen mode
console.log(`Normal String \nNext String`);
/* output: 
Normal String 
Next String 
*/

console.log(String.raw`Normal String \nNext String`); 
// output: Normal String \nNext String 
Enter fullscreen mode Exit fullscreen mode

Another interesting feature that template literals offer, is the ability to tag strings with a function and be able to manipulate the string contents in whichever way you want. Check the example below to see the syntax for a tagged template string.

function tag() {
  return "Hello";
}

const name = "Daito";
const country = "Japan";
const description = tag`My friend ${name} is from ${country}.`;

console.log(description); // Hello;
Enter fullscreen mode Exit fullscreen mode

As seen in the example above, the variable "description" has the name of the function right before the string (it's been tagged). Once it has been put in place, the function gets access to an array of strings and each of the expressions that are present, Although, with the help of the ES6 spread operator, we can pass all the expressions at once which will create an array. In the example above we will get access to the following:

An array of strings:

  1. "My friend "
  2. " is from "
  3. "."

An array of expressions:

  1. "Daito"
  2. "Japan"

Now we can use these strings and expressions as we please. In the following example, the function has 2 parameters (strings and expressions) and then displays the results to the console.

function tag(strings, ...expressions) {
  console.log(strings, expressions);
}

const name = "Daito";
const country = "Japan";
const description = tag`My friend ${name} is from ${country}.`;

// Output: ↓ 
// ["My friend ", " is from ", "."] ["Daito", "Japan"];
Enter fullscreen mode Exit fullscreen mode

In case that we didn't have any starting and ending values in the description string, it will be automatically filled with an empty string at the beginning and end, which would look something like this.

const description = tag`${name} is from ${country}`;
// Output: ↓ 
// ["", " is from ", ""] ["Daito", "Japan"];
Enter fullscreen mode Exit fullscreen mode

Now that we have this, the possibilities are endless since everything is running through a function, we can manipulate our strings the way we want.

function tag(strings, ...expressions) {
  let str = ``;

  for (const [i, expression] of expressions.entries()) {
    str += `${strings[i]}${expression.toUpperCase()}`;
  }

  str += strings[strings.length - 1];

  return str;
}

const name = "Daito";
const country = "Japan";
const age = "24";
const description = tag`My friend ${name} is from ${country} and he is ${age} years old.`;

console.log(description); // Output: ↓ 
// My friend DAITO is from JAPAN and he is 24 years old. 
Enter fullscreen mode Exit fullscreen mode

or with a reducer function: (see example below)

function tag(strings, ...expressions) {
  const str = expressions.reduce((acu, currentValue, i) => {
    return `${acu}${currentValue.toUpperCase()}${strings[i + 1]}`;
  }, strings[0]);

  return str;
}

const name = "Daito";
const country = "Japan";
const age = "24";
const description = tag`My friend ${name} is from ${country} and he is ${age} years old.`;

console.log(description); // Output: ↓ 
// My friend DAITO is from JAPAN and he is 24 years old.
Enter fullscreen mode Exit fullscreen mode

As always there are more interesting things that you can do with tagged template literals rather than just changing some of the text to uppercase. I hope this gives you a good start. Thank you for reading my post and see you in the next one. 😊

💖 💪 🙅 🚩
marlonry
marlonry

Posted on February 7, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

5 important JavaScript array methods
learning 5 important JavaScript array methods

February 4, 2021

Understanding Tagged Template Literals
learning Understanding Tagged Template Literals

February 7, 2021