javascriptecmascript-6template-literals

How to place a backtick (`) inside a template literal?


How can I write a template literal in ECMAScript 6 that will contain backticks (`) in and by itself, (i.e. nested backticks)?

For example:

var query = `
  UPDATE packet
  SET
  `association` = "3485435",
  `tagname` = "associated"
 `

The reason I need it:

It's quite obvious in my code example above.

I'm trying to build node-mysql queries as Strings and store them in a variable for passing them to MySQL. The MySQL query syntax requires back ticks for UPDATE-style queries.


Solution

  • See 11.8.6 Template Literal Lexical Components

    A template without substitutions is defined as

    NoSubstitutionTemplate ::
        ` TemplateCharactersopt `

    where a template character is

    TemplateCharacter ::
        $ [lookahead ≠ { ]
        \ EscapeSequence
        LineContinuation
        LineTerminatorSequence
        SourceCharacter but not one of ` or \ or $ or LineTerminator

    Therefore, ` can't be a template character unless you escape it by preceding it with \.