Today I Learned - Rocky Kev

TIL Tagged Templates

POSTED ON:

TAGS:

Today I learned of Tagged Templates!

Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.

The MDN example:

const person = "Mike";
const age = 28;

function myTag(strings, personExp, ageExp) {
const str0 = strings[0]; // "That "
const str1 = strings[1]; // " is a "
const str2 = strings[2]; // "."

const ageStr = ageExp > 99 ? "centenarian" : "youngster";

// We can even return a string built using a template literal
return `${str0}${personExp}${str1}${ageStr}${str2}`;
}

// This breaks the string into all of its wild pieces.
const output = myTag`That ${person} is a ${age}.`;

console.log(output);

MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates

The html example:

via https://www.reddit.com/r/webdev/comments/10wap56/did_you_know_about_javascript_tag_functions/


Related TILs

Tagged:

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL How to steal localData using an XSS attack

But that's just a red flag that opens the door to bigger issues.

TIL Clear-Site-Data

The Clear-Site-Data header clears browsing data (cookies, storage, cache) associated with the requesting website. It allows web developers to have more control over the data stored by a client browser for their origins.