Please support this book: buy it or donate

12. Template Literal Revision



The ECMAScript proposal “Template Literal Revision” by Tim Disney gives the innards of tagged template literals more syntactic freedom.

12.1. Tag functions and escape sequences

With tagged template literals, you can make a function call by mentioning a function before a template literal:

  1. > String.raw`\u{4B}`
  2. '\\u{4B}'

String.raw is a so-called tag function. Tag functions receive two versions of the fixed string pieces (template strings) in a template literal:

  • Cooked: escape sequences are interpreted. \u{4B} becomes 'K'.
  • Raw: escape sequences are normal text. \u{4B} becomes '\u{4B}'. The following tag function illustrates how that works:
  1. function tagFunc(tmplObj, substs) {
  2. return {
  3. Cooked: tmplObj,
  4. Raw: tmplObj.raw,
  5. };
  6. }

Using the tag function:

  1. > tagFunc`\u{4B}`;
  2. { Cooked: [ 'K' ], Raw: [ '\\u{4B}' ] }

For more information on tag functions, consult Sect. “Implementing tag functions” in “Exploring ES6”.

12.2. Problem: some text is illegal after backslashes

The problem is that even with the raw version, you don’t have total freedom within template literals in ES2016. After a backslash, some sequences of characters are not legal anymore:

  • \u starts a Unicode escape, which must look like \u{1F4A4} or \u004B.
  • \x starts a hex escape, which must look like \x4B.
  • \ plus digit starts an octal escape (such as \141). Octal escapes are forbidden in template literals and strict mode string literals. That prevents tagged template literals such as:
  1. latex`\unicode`
  2. windowsPath`C:\uuu\xxx\111`

12.3. Solution

The solution is drop all syntactic restrictions related to escape sequences. Then illegal escape sequences simply show up verbatim in the raw representation. But what about the cooked representation? Every template string with an illegal escape sequence is an undefined element in the cooked Array:

  1. > tagFunc`\uu ${1} \xx`
  2. { Cooked: [ undefined, undefined ], Raw: [ '\\uu ', ' \\xx' ] }