A function identified immediately before a template literal is used to interpret it, in what is called a tagged template literal. The tag function can return a string, but it can also return any other type of value.
The first argument to the tag function, strings
, is an Array of each constant piece of the literal. The remaining arguments, ...substitutions
, contain the evaluated values of each ${}
substitution expression.
function settings(strings, ...substitutions) {
const result = new Map();
for (let i = 0; i < substitutions.length; i++) {
result.set(strings[i].trim(), substitutions[i]);
}
return result;
}
const remoteConfiguration = settings`
label ${'Content'}
servers ${2 * 8 + 1}
hostname ${location.hostname}
`;
Map {"label" => "Content", "servers" => 17, "hostname" => "stackoverflow.com"}
The strings
Array has a special .raw
property referencing a parallel Array of the same constant pieces of the template literal but exactly as they appear in the source code, without any backslash-escapes being replaced.
function example(strings, ...substitutions) {
console.log('strings:', strings);
console.log('...substitutions:', substitutions);
}
example`Hello ${'world'}.\n\nHow are you?`;
strings: ["Hello ", ".\n\nHow are you?", raw: ["Hello ", ".\\n\\nHow are you?"]]
substitutions: ["world"]