aderaaij
11/12/2017 - 8:12 PM

ES6 Tagged Templates 2

An example of 'tagging' an ES6 template string with a function. The function takes in the string as an argument and returns strings broken up by values as an array and the values as the rest of the arguments.

const dict = {
    HTML: 'Hyper Text Markup Language',
    CSS: 'Cascading Style Sheets',
    JS: 'JavaScript'
};

/* Create the function we tag onto the template string. Tagging it to a template
string automatically returns the strings seperated by values as an array (strings)
and gives the values as the rest of the argument. */
function addAbrriviations(strings, ...values) {
    /* We use the es6 rest operator to get the rest of all the values */
    const abbreviated = values.map(value => {
        if(dict[value]) {
            return `<abbr title='${dict[value]}'>${value}</abbr>`;
        }
        return value;
    });
    
    // Using array.reduce which takes in a function and an optional initial value
    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
    return strings.reduce((sentence, string, i) => {
        return `${sentence}${string}${abbreviated[i] || ''}`
    }, '');
  }

  const first = 'Arden';
  const last = 'de Raaij';
  const sentence = addAbrriviations`Hello, my name is ${first} ${last} and I love to code ${'HTML'}, ${'CSS'} and ${'JS'} `;
  const p = document.createElement('p');
  
  p.innerHTML = sentence;
  document.body.appendChild(p);