9

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?

gyre
  • 16,369
  • 3
  • 37
  • 47
blz
  • 837
  • 7
  • 20
  • \ is used to escape a character – mehulmpt Mar 05 '17 at 04:57
  • If you want a solution with slightly less typing you could use ``let path = String.raw`C:\path\to\directory` + '\\'``. (I find that easier to read, too, because a space right before the closing ` isn't necessarily obvious.) – nnnnnn Mar 05 '17 at 05:18

2 Answers2

3

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)
Lonnie Best
  • 9,936
  • 10
  • 57
  • 97
gyre
  • 16,369
  • 3
  • 37
  • 47
0

According to https://hacks.mozilla.org/2015/05/es6-in-depth-template-strings-2/ escape sequences are left untouched, aside from \$ \{ and \`, in template strings. Thus one cannot escape the escape character. Based on this it looks like your solution is the best way to achieve your goal.

JeremiahB
  • 896
  • 8
  • 15