JS: Tagged Template String

By Xah Lee. Date: . Last updated: .

What is tagged template string

(new in ECMAScript 2015)

There's a special notation to call a function, called tagged template string. The syntax is:

functionName`…`

When function is called this way, the function is fed one or more arguments based on the template string the `…`.

The first argument is a array, and each elements are literal segment of the template string. That is, the template string is split into parts, separated by the pattern ${}. The rest arguments, are the embeded expressions of the template string.

// tagged template function call. show args received

const ff = (...x) => x;

console.log(ff`a`);
// [ [ "a" ] ]

console.log(ff`a ${1 + 1}`);
// [ [ "a ", "" ], 2 ]

console.log(ff`a ${1 + 1} b ${3}`);
// [ [ "a ", " b ", "" ], 2, 3 ]

Purpose of tagged template

Tagged template let you modify template in a flexible way.

instead of just printing a template string output = `…` you can modify it by adding a function output = f`…`.

Javascript code example to reconstruct template string

// reconstruct template string

const fg = (...args) => {
 const xb = args.slice(1).concat("");
 return args[0].flatMap((x, i) => [x, xb[i]]).join("");
};

// test
console.assert(fg`a${1}b${2}` === "a1b2");
console.assert(fg`a${1}b${2}c${3}` === "a1b2c3");

console.assert(`a` === fg`a`);
console.assert(`${1}` === fg`${1}`);
console.assert(`a${1}` === fg`a${1}`);
console.assert(`${1}b` === fg`${1}b`);
console.assert(`a${1}${2}` === fg`a${1}${2}`);

JavaScript. String