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 qu
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"`
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:
`\``
Use \`, it seems to work for me in the latest Chrome.
ES6 has new features:
Which make working with strings easier. You wrap your text in `backticks`.
With this we can:
Interpolate variables
let foo = "abc";
console.log(`Welcome ${foo}`); // Welcome abc
Interpolate any kind of expression
console.log(`2+3 = ${2+3}`) // 2+3 = 5
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"
Cleaner syntax for multi-line string
let text = `foo is bar
bar is foo`
console.log(text);
//"foo is bar
//bar is foo"
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
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.
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).
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 \.