Template literals with nested backticks(`) in ES6

JavascriptEcmascript 6

Javascript Problem Overview


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.

  • The only way I can have them look neat & tidy is by using template literals, otherwise the queries using regular single-line strings look awful because they end up being very long is some cases.

  • I also want to avoid terminating lines using \n as it's cumbersome.

Javascript Solutions


Solution 1 - Javascript

From ES6 In Depth: Template strings by Jason Orendorff:

>If you need to write a backtick inside a template string, you must escape it with a backslash: `\`` is the same as "`".

Your query should be:

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

Solution 2 - Javascript

See 11.8.6 Template Literal Lexical Components

A template without substitutions is defined as

NoSubstitutionTemplate ::
</b> <i>TemplateCharacters</i><sub>opt</sub> <b>

where a template character is

TemplateCharacter ::
$ [lookahead ≠ { ]
</b> EscapeSequence
LineContinuation
LineTerminatorSequence
SourceCharacter but not one of ` or </b> or $ or LineTerminator

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

Solution 3 - Javascript

If you want to use an apostrophe in a string made with apostrophes, you escape it with a backslash, like this:

'\''

Similarly, if you want to use a backtick in a template literal, you have to escape it with a backslash:

`\``

Solution 4 - Javascript

As mentioned in other answers, you can escape the backtick ` with a backslash, like \`.

var tripleBacktickExample = `
\`\`\`python
# This JavaScript string contains some example Markdown that
# uses triple-backticks to delimit a Python code block.
\`\`\`
`

However, if you need very many backticks in a row ````` inside the template literal, it could be more readable to put them within a normal string that is inside a placeholder, like ${'`````'} or ${"`````"}.

var tripleBacktickExample = `
${'```'}python
# This JavaScript string contains some example Markdown that
# uses triple-backticks to delimit a Python code block.
${'```'}
`

Solution 5 - Javascript

Use \`, it seems to work for me in the latest Chrome.

Solution 6 - Javascript

Personally I consider ES6 template literals to be inadequate for SQL (and Markdown) principally because you can't use backtick characters. I wish they would add triple-quoted strings to fix this properly.

In the meantime, since you're probably using a transpiler for ES6 anyway, you might consider using triplet (disclaimer: I am the author).

Solution 7 - Javascript

To escape all special characters, not just the backticks:

let str = '`Hello`\\n${world}';
let escacped = str.replace(/\\|`|\$/g, '\\$&');
console.log(eval('`' + escaped + '`') === str); // test

I needed this for some code generation stuff. The str was the content of a JavaScript file and the goal was to put this content into a string literal variable into another generated JavaScript file.

Sadly it seems there is (2019) no native JavaScript function for this escaping. The characters that needs to be replaced are: `, $ and \.

Solution 8 - Javascript

ES6 has new features:

  • Template literals
  • Tagged template literals (tagged templates)

Which make working with strings easier. You wrap your text in `backticks`.

With this we can:

  1. Interpolate variables

     let foo = "abc";
    
     console.log(`Welcome ${foo}`); // Welcome abc
    
  2. Interpolate any kind of expression

     console.log(`2+3 = ${2+3}`) // 2+3 = 5
    
  3. Declare strings with both ' and " quotation marks without having to escape anything.

     let foo = `foo is 'bar', "bar" is foo`
    
     console.log(foo); // "foo is 'bar', "bar" is foo"
    
  4. Cleaner syntax for multi-line string

     let text = `foo is bar
    
     bar is foo`
    
     console.log(text);
    
     //"foo is bar
    
     //bar is foo"
    
  5. Tagged templates, we can pass template literals to a function, here is how:

     let person = 'Mike';
     let age = 28;
    
     let output = myTag `that ${ person } is ${ age }`;
    
     function myTag(strings, personExp, ageExp) {
    
         // strings[0] gets value "that "
         // strings[1] gets value " is "
         // personExp  gets value " Mike "
         // ageStr     gets value "28"
    
         return strings[0] + personExp + strings[1] + ageExp;
     }
    
     console.log(output);
    
     // that Mike is 28
    
  6. String.raw, we can get the raw form, here is the example:

     let text = String.raw `The "\n" newline won't result in a new line.'
     console.log(text);
     // The "\n" newline won't result in a new line.
    

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnicholaswminView Question on Stackoverflow
Solution 1 - Javascripttt9View Answer on Stackoverflow
Solution 2 - JavascriptOriolView Answer on Stackoverflow
Solution 3 - JavascriptMichał PerłakowskiView Answer on Stackoverflow
Solution 4 - JavascriptRory O'KaneView Answer on Stackoverflow
Solution 5 - JavascriptdamdView Answer on Stackoverflow
Solution 6 - JavascriptSystemParadoxView Answer on Stackoverflow
Solution 7 - JavascriptfloriView Answer on Stackoverflow
Solution 8 - JavascriptManishz90View Answer on Stackoverflow