Blog

Tagged Template Literals
Posted on September 10, 2020 in JavaScript by Matt Jennings

Definition

The ability to run a template string through a function, and have control how the actual template string is made, along with the interpolated strings.

Code Example

var bear = 'Grizzly';
var result = html`<div>${bear}</div>`;

function html(strings, expr) {
  var divTagWrapper = document.createElement('div');
  var divTag = strings.join('');
  var divTagWithClassAndExpr = divTag.replace(/div>/, `div class="bear">${expr}`);
  return divTagWithClassAndExpr;
}

document.body.insertAdjacentHTML('afterbegin', result);
// <div class="bear">Grizzly</div> element and text
// is inserted right after the opening <body> HTML tag

Another Code Example to Uppercase all Variables inside an Interpolated String

function upper(strings, ...values) {
  var ret = '';
  for(let i = 0; i < strings.length; i++) {
    if(i > 0) {
      ret += String(values[i-1].toUpperCase());  
    }
    ret += strings[i];
  }
  return ret;
}

var name = "kyle";
var twitter = "getify";
var topic = "JS Recent Parts";

console.log(upper`Hello ${name} (@${twitter}), welcome to ${topic}!` === 'Hello KYLE (@GETIFY), welcome to JS RECENT PARTS!');
// true

Leave a Reply