简体   繁体   中英

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?

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"

Try using String.raw :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM