Tagged strings

suggest change

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"]

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Template Literals:
* Syntax
* Tagged strings

Table Of Contents
10 Template Literals
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde