Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`String.raw` when last character is `\`

Tags:

javascript

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?

like image 798
blz Avatar asked Mar 05 '17 04:03

blz


People also ask

What does \r mean in a string?

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 .

Which character prefixed before a string as raw string?

Python raw string is created by prefixing a string literal with 'r' or 'R'. Python raw string treats backslash (\) as a literal character.

What is `` in JS?

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.

What does \r mean Python?

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.


1 Answers

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)
like image 167
gyre Avatar answered Oct 15 '22 09:10

gyre