问题
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