简体   繁体   English

如何防止字符 '\\' 转义 ES6 模板字符串?

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

In ES6, I can do something like this:在 ES6 中,我可以这样做:

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

That will automatically replace ${myVar} with the actual value of myVar .这将自动替换${myVar}与实际值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 :尝试使用String.raw

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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