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