šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Tagged template literals in Javascript

In ES6 the templated literals were added in Javascript. They are used to interpolate values in a string.

const name = 'Tom'
const age = 20;
const myString = `The name is ${name} and the age is ${age}.`;
/* 
myString is now "The name is Tom and the age is 20."
before  ES6 the templated literals we had to write:
myString = "The name is " + name + " and the age is " + age "."
*/

So, this made things a bit more elegant when concatenating strings.

But we can do more than this. We can define tagged template literals. Basically, they are a combination of a tag function and a string template literal. What's returned from the tag function will determine the final format of the string.

Let's say we want to show a string like this one in the below picture.

The basic string literal will just alow use to write this:

const text = `${p.name} is ${p.age} years old.`;

However, with the tagged template literals we can say:

const text = setHighlightTags `${p.name} is ${p.age} years old.`;

We can name the tag function however we want. In our example the setHighlightTags is defined as:

function setHighlightTags(strings, ...values) {
   let str = '';
   strings.forEach((string, i) => {
       str += string;
       if(values[i]) 
          str += `<span class='hl'>${values[i]} </span>`;
   });
   return str;
}

And the .hl CSS class has just some simple rules:

.hl {
    background-color: yellow;
    padding: 2px 10px;
}

And that's pretty much all we need. We can get more creative when we need it. There are libraries, like styled-components (React) or chalk (for colorful logs) that take this feature to the next level.

If you want you can read more about it here. Also, check out below the full codepen for this example:

See the Pen
tagged-template-literals
by JS Craft (@js-craft)
on CodePen.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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