eslint-plugin-unicorn
eslint-plugin-unicorn copied to clipboard
Rule proposal: `prefer-string-raw`
Description
To avoid escape \.
Fail
console.log('"\\" found.');
const directory = "C:\\windows\\style\\path";
new RegExp('foo\\.bar')
Pass
console.log(String.raw`"\" found.`);
const directory = String.raw`C:\windows\style\path`;
new RegExp(String.raw`foo\.bar`)
const foo = '\\ `';
// Use `String.raw` will need escape `
const foo = '\\ ${foo}';
// Use `String.raw` will need escape $ or `{`
// Places can't use a tagged template
"A directive\\"
import foo from "./foo\\bar.js";
const foo = {
'\\': 'a non-computed key'
}
This rule can also check when building a tagged function like this, but it's hard to detect such pattern.
Seems useful sometimes. I think the rule should not trigger when the string in question contains other escape sequences besides \\ because using String.raw on that would break those other sequences, for example:
console.log(`"\\" found. \nok`);
@sindresorhus Thoughts?
Accepted
@fisker @sindresorhus, is this rule compelling enough to have in the “recommended” set? I normally try to abide by plugin defaults, but I’m struggling here. While C#/Python syntax for raw is short, JavaScript syntax is long and ugly. This is personal preference, but the examples in the documentation feel to me like they are worse after the recommended change. Also, if the reader is not familiar with template literals, the JS syntax looks wrong/invalid. According to mdn, raw is the “only built-in template literal tag” which makes me think it won’t be familiar to a lot of people. To be clear, I don’t object to the rule itself, I’m just questioning whether it should be recommended?
the examples in the documentation feel to me like they are worse after the recommended change
Why is that? Escaped \\ is ugly to me.
The console.log and RegExp examples are almost twice as long after adding String.raw - and the first/most important parameter to both functions is partially obscured because it's prefixed by String.raw.
I tired to enable this rule, but ended up disabling it because the only cases where I use backslashes is in RegExp strings like "[^\\/]", and I found the readability reduced because String.raw is not well known and the intend of avoiding to escape a single character is not obvious.
Should not be in recommended. This kills performance and VSCode syntax highlighting doesn't know how to handle it:
console.time('before')
for (let i = 0; i < 100000; i++) 'C:\\windows\\style\\path'
console.timeEnd('before') // 1.935 ms
console.time('after')
for (let i = 0; i < 100000; i++) String.raw`C:\windows\style\path`
console.timeEnd('after') // 47.016 ms
// Around: 25x slower