String.raw
is very useful. For example:
let path = String.raw`C:\path\to\file.html`
However, when the last character of the template string is \
, it becomes an syntax error.
let path = String.raw`C:\path\to\directory\`
Uncaught SyntaxError: Unterminated template literal
Tentatively, I use this method.
let path = String.raw`C:\path\to\directory\ `.trimRight()
Can I write template string which last character is \
using String.raw
?
The r means that the string is to be treated as a raw string, which means all escape codes will be ignored. For an example: '\n' will be treated as a newline character, while r'\n' will be treated as the characters \ followed by n .
Python raw string is created by prefixing a string literal with 'r' or 'R'. Python raw string treats backslash (\) as a literal character.
Although single quotes and double quotes are the most popular, we have a 3rd option called Backticks ( `` ). Backticks are an ES6 feature that allows you to create strings in JavaScript. Although backticks are mostly used for HTML or code embedding purposes, they also act similar to single and double quotes.
In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return.
Here are a few different possible workarounds. My favorite is probably creating a custom template tag dir
to solve the problem for you. I think it makes the syntax cleaner and more semantic.
let path
// Uglier workarounds
path = String.raw `C:\path\to\directory${`\\`}`
path = String.raw `C:\path\to\directory`+`\\`
path = `C:\\path\\to\\directory\\`
// Cleanest solution
const dir = ({raw}) => raw + `\\`
path = dir `C:\path\to\directory`
console.log(path)
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