Why Can't String.raw End With A Backslash?
Solution 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.
Solution 2:
Ending \`
is always parsed as escaped `
symbol, meaning there's no matching closing backtick for a template literal. This makes it less consistent regarding how backslash can be used with String.raw
.
For more special cases a string can be padded per need basis with characters that aren't expected in resulting sting.
It can be a newline:
consttrimmedLine = (...args) => String.raw(...args).replace(/^(?:\r?\n|)([\s\S]*?)(?:\r?\n|)$/, '$1')
// "C:\Program Files\7-Zip\"
trimmedLine`
C:\Program Files\7-Zip\
`
A space:
consttrimmedSpace = (...args) => String.raw(...args).replace(/^([\s\S]*?) ?$/, '$1')
trimmedSpace`C:\Program Files\7-Zip\ `// "C:\Program Files\7-Zip\" with no space
trimmedSpace`C:\Program Files\7-Zip\ `// "C:\Program Files\7-Zip\ " with 1 space
And so on.
Even if a string shouldn't be trimmed, a helper can cover this by removing exactly one whitespace character, so extra one could be added to present in resulting string.
Post a Comment for "Why Can't String.raw End With A Backslash?"