Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template literals with nested backticks(`) in ES6

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.

like image 683
nicholaswmin Avatar asked Mar 04 '16 18:03

nicholaswmin


People also ask

How do you use backticks in template literals?

In that case, the template literal is passed to your tag function, where you can then perform whatever operations you want on the different parts of the template literal. To escape a backtick in a template literal, put a backslash ( \ ) before the backtick. Dollar signs can be escaped as well to prevent interpolation.

What are the template literals in ES6?

Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions. Before ES6, template literals were called as template strings.

Can you concatenate template literals?

When you use regular template literals, your input is passed to a default function that concatenates it into a single string. An interesting thing is that you can change it by preceding the template literal with your function name that acts as a tag. By doing it, you create a tagged template.

Does es5 have template literals?

ECMAScript 2015 presents a new type of string literal called template literal. Fortunately it allows to embed JavaScript expressions into place holders ${expression} and create strings as easy as a pie. No more redundant concatenation operators and single quotes. The template literal makes the string easy to follow.


1 Answers

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"` 
like image 104
tt9 Avatar answered Sep 20 '22 17:09

tt9