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:

function_name`text`

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

The first argument to the function is a array. Each elements are literal segment of the template string. That is, the template string is split into parts, separated by the pattern ${text}.

The rest arguments, are the embeded expressions of the template string.

// tagged template function call. show args received

// ff just return its args as a array
const ff = (...rest) => rest;

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

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

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

Purpose of tagged template

Tagged template let you modify template in a flexible way.

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

Example. 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}`);