Javascript String Template Literal Tag Functions

Introduction

Template literals tag functions define custom interpolation behavior.

let a = 6; //from w  w w  .j av  a  2  s. c  om
let b = 9; 
            
function simpleTag(strings, aVal, bVal, sum) { 
   console.log(strings); 
   console.log(aVal); 
   console.log(bVal); 
   console.log(sum); 
              
   return 'foobar'; 
} 
let untaggedResult = `${ a } + ${ b } = ${ a + b }`; 
let taggedResult = simpleTag`${ a } + ${ b } = ${ a + b }`; 
              
console.log(untaggedResult); 
console.log(taggedResult);   

The following code uses the spread operator to combine them into a single collection:

let a = 6; //from   www  .ja v  a 2 s .  co m
let b = 9; 
              
function simpleTag(strings, ...expressions) { 
   console.log(strings); 
   for(const expression of expressions) { 
      console.log(expression); 
   } 
   return 'foobar'; 
} 
let taggedResult = simpleTag`${ a } + ${ b } = ${ a + b }`; 
console.log(taggedResult);  // "foobar" 

The following code "zip" the strings and the evaluated expressions together into the default returned string:

let a = 6; /*from   w ww .j a  va  2 s .com*/
let b = 9; 
              
function zipTag(strings, ...expressions) { 
   return strings[0] +  
          expressions.map((e, i) => `${e}${strings[i + 1]}`).join(''); 
} 
              
let untaggedResult =     `${ a } + ${ b } = ${ a + b }`; 
let taggedResult = zipTag`${ a } + ${ b } = ${ a + b }`; 
console.log(untaggedResult);  
console.log(taggedResult);  



PreviousNext

Related