Template literals with nested backticks(`) in ES6

Viewed 32012

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.

8 Answers

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 \.

Related