How to prevent the character '\' from escaping ES6 template strings?

André Pena picture André Pena · Jun 27, 2015 · Viewed 8k times · Source

In ES6, I can do something like this:

let myString = `My var: ${myVar}`;

That will automatically replace ${myVar} with the actual value of myVar. Perfect.

But what if I have something like this?

let myString = `My var: \${myVar}`;

The character \ is escaping the ${} construct. It just becomes a regular string.

How can I make \ not to escape in this case?

Answer

Bergi picture Bergi · Jun 27, 2015

If you want to have a literal backslash in your template string, you will need to escape it:

let myVar = "test";
let myString = `My var: \\${myVar}`; // "My var: \test"