Reputation: 22949
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 backticks for UPDATE
-style queries.
The only way I can have them look neat and 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.
Upvotes: 88
Views: 52114
Reputation: 1139
In my case I was injecting an HTML file as a string literal (with new lines) into a TypeScript file on the fly while transpiling with esbuild.
The gist being something similar to the following example:
// ...
let html = fs.readFileSync('./src/index.html', 'utf8');
// This escapes all instances of the three special characters
// that would break a backtick string literal definition: ` \ $
html = html.replace(/[`\\$]/g, '\\$&');
// ...
tsContents = tsContents.replace(
/let html = [^;]+;/,
() => `let html = \`${minified}\`;`,
);
return {
contents,
loader: 'ts',
};
The "magic" portion being:
.replace(/[`\\$]/g, '\\$&');
Upvotes: 3
Reputation: 9790
You can use a specific combination of characters to replace the backticks and use replaceAll
afterwards to swap them.
Example:
var backtickReplace = `|replace_me_with_backtick_`;
var example = `This is a ${backtickReplace}back tick${backtickReplace}!`;
var result = example.replaceAll(backtickReplace, "`");
console.log(result);
Upvotes: -1
Reputation: 394
I found it easier to wrap the backticks in quotation marks to be easier. Here is an example you might use to start a code block in markdown:
const str = `${'```'}JavaScript`; // then the rest of whatever you need
So for your exact example
var query = `
UPDATE packet
SET
${'`'}association${'`'} = "3485435",
${'`'}tagname${'`'} = "associated"
`
Upvotes: 2
Reputation: 15837
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 \
.
Upvotes: 6
Reputation: 2624
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.
Upvotes: -6
Reputation: 8647
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).
Upvotes: 1
Reputation: 92501
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:
`\``
Upvotes: 12
Reputation: 30388
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.
${'```'}
`
Upvotes: 7
Reputation: 6069
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"`
Upvotes: 98
Reputation: 288080
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 \
.
Upvotes: 10