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
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.
${'```'}
`
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 \.