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

String.raw very useful. For example:

 let path = String.raw`C:\path\to\file.html` 

However, when the last character of the pattern string \ , it becomes a syntax error.

 let path = String.raw`C:\path\to\directory\` 

Untrained SyntaxError: listing without a template instance

Tentatively, I use this method.

 let path = String.raw`C:\path\to\directory\ `.trimRight() 

Is it possible to write a template string for which the last \ character is used by String.raw ?

+7
javascript
source share
2 answers

Here are a few different workarounds. My favorite probably creates a special dir template tag to solve the problem for you. I think this makes the syntax cleaner and more meaningful.

 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) 
+3
source share

According to https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/ escape sequences remain untouched except for \ $ \ {and \ `in the pattern strings. Thus, an escape character cannot be avoided. Based on this, it seems that your decision is the best way to achieve your goal.

0
source share

All Articles