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

String.raw is very useful. For example:

let path = String.raw`C:pathtofile.html`

However, when the last character of the template string is , it becomes an syntax error.

let path = String.raw`C:pathtodirectory`

Uncaught SyntaxError: Unterminated template literal

Tentatively, I use this method.

let path = String.raw`C:pathtodirectory `.trimRight()

Can I write template string which last character is using String.raw ?


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:pathtodirectory${``}`
path = String.raw `C:pathtodirectory`+``
path = `C:pathtodirectory`

// Cleanest solution
const dir = ({raw}) => raw + ``

path = dir `C:pathtodirectory`

console.log(path)

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.

链接地址: http://www.djcxy.com/p/38616.html

上一篇: LD:必要的名称是什么?

下一篇: 当最后一个字符是`\`时``String.raw`