JS: Tagged Template String
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
- JS: String Overview
- JS: Quote String
- JS: Apostrophe Delimiter String
- JS: Template String
- JS: String Escape Sequence
- JS: Unicode Escape Sequence
- JS: String Operations
- JS: Iterate String
- JS: String Index Code Unit
- JS: Count Chars in String 📜
- JS: String.raw
- JS: Tagged Template String
- JS: Regular Expression Functions
- JS: Convert String and Number
- JS: String (class)
- JS: String Constructor
- JS: String.prototype