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?
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.
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.
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.
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.
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`
____ _
| _ \ (_)
| |_) | ___ _ __ __ _ _
| _ < / _ | '__/ _' | |
| |_) | __| | | (_| | |
|____/ \___|_| \__, |_|
__/ |
|___/
`
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With