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?
Update: Another example where the single backslash doesn't do what I'd like is:
let str1 = "folder";
let str2 = "subfolder";
let fileName = "file.txt"
let path = String.raw`\${str1}\${str2}\${fileName}`;
console.log(path);
While I was hoping for this output:
\folder\subfolder\file.txt
Instead it outputs:
\${str1}\${str2}\${fileName}
The backslash escapes the dollar sign's special meaning. So, this is yet another circumstance where you still have to double up those backslashes :(
If you want to include a backslash character itself, you need two backslashes or use the @ verbatim string: var s = "\\Tasks"; // or var s = @"\Tasks"; Read the MSDN documentation/C# Specification which discusses the characters that are escaped using the backslash character and the use of the verbatim string literal.
The r means that the string is to be treated as a raw string, which means all escape codes will be ignored. For an example: '\n' will be treated as a newline character, while r'\n' will be treated as the characters \ followed by n .
Python Raw String and QuotesWhen a backslash is followed by a quote in a raw string, it's escaped. However, the backslash also remains in the result. Because of this feature, we can't create a raw string of single backslash. Also, a raw string can't have an odd number of backslashes at the end.
Character combinations consisting of a backslash (\) followed by a letter or by a combination of digits are called "escape sequences." To represent a newline character, single quotation mark, or certain other characters in a character constant, you must use escape sequences.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With