Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 544
André Pena Avatar asked Jun 27 '15 20:06

André Pena


People also ask

What is string interpolation in ES6?

String interpolation is a new feature of ES6, that can make multi-line strings without the need for an escape character. We can use apostrophes and quotes easily that they can make our strings and therefore our code easier to read as well.

What is ES6 template string?

Template literals are a new feature introduced in ECMAScript 2015/ ES6. It provides an easy way to create multiline strings and perform string interpolation. Template literals are the string literals and allow embedded expressions.

Do I need to escape in JavaScript string?

TL;DR there's no need for crazy hacks like string concatenation or char literal escapes — just escape it as such: var snaphtml = '<\/script>'; Also, note that this is only necessary for inline scripts.

What is escape character in JavaScript?

Escape characters are characters that can be interpreted in some alternate way then what we intended to. To print these characters as it is, include backslash '\' in front of them. Following are the escape characters in JavaScript − Code. Result.


2 Answers

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"
like image 98
Bergi Avatar answered Oct 19 '22 15:10

Bergi


Try using String.raw:

const name = String.raw`
  ____                 _ 
 |  _ \               (_)
 | |_) | ___ _ __ __ _ _ 
 |  _ < / _ | '__/ _' | |
 | |_) |  __| | | (_| | |
 |____/ \___|_|  \__, |_|
                  __/ |  
                 |___/   
`
like image 42
Bruno Avatar answered Oct 19 '22 14:10

Bruno