Why can't String.raw end with a backslash?

混江龙づ霸主 提交于 2020-05-15 05:25:31

问题


String.raw can be used to create a string that contains backslashes, without having to double up those backslashes.

Historically, you'd need to double up backslashes when creating a string:

let str = "C:\\Program Files\\7-Zip";
console.log(str);

String.raw allows your code to show the path without doubled backslashes:

let str = String.raw`C:\Program Files\7-Zip`;
console.log(str);

The above code works fine, but today I discovered that it doesn't work if the raw string ends with a backslash:

let str = String.raw`Can't End Raw With Backslash\`;
console.log(str);

The above snippet produces this error:

{
  "message": "SyntaxError: `` literal not terminated before end of script",
  "filename": "https://stacksnippets.net/js",
  "lineno": 14,
  "colno": 4
}

Why is this an exception?


回答1:


It can, but remember that there's the "literal" character and the backslash character. You're asking for a literal backtick. Ask for a literal backslash:

let str = String.raw`...\\`;

Any character immediately following a backslash is treated as its literal version, regardless of what it is. String.raw can work around some of those limitations, but not all. It suppresses interpolation of things like \n but can't prevent you from accidentally adding a literal backtick.



来源:https://stackoverflow.com/questions/61416857/why-cant-string-raw-end-with-a-backslash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!