Andre Pena
Andre Pena

Reputation: 59336

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

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?

Upvotes: 13

Views: 11936

Answers (2)

Bruno
Bruno

Reputation: 6449

Try using String.raw:

const name = String.raw`
  ____                 _ 
 |  _ \               (_)
 | |_) | ___ _ __ __ _ _ 
 |  _ < / _ | '__/ _' | |
 | |_) |  __| | | (_| | |
 |____/ \___|_|  \__, |_|
                  __/ |  
                 |___/   
`

Upvotes: 14

Bergi
Bergi

Reputation: 664599

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"

Upvotes: 18

Related Questions