unicorn/prefer-string-raw

Require String.raw for strings that escape backslashes

fixable

In a normal string you write every backslash twice, which makes a Windows path or a regex source hard to read and easy to get wrong. In a String.raw template you write it once.

The rule skips a string that has another escape such as \n, ends with a backslash, or contains a backtick or ${. String.raw can't express those.

--fix rewrites the string to a String.raw template.

Configure#

Off by default. To turn it on:

bunfig.toml
[lint.rules]
"unicorn/prefer-string-raw" = "error" # or "warn"

Examples#

example.js2 problems
const logs = "C:\\Users\\ada\\logs";
const version = new RegExp("\\d+\\.\\d+");
example.jsNo problems
const logs = String.raw`C:\Users\ada\logs`;
const version = new RegExp(String.raw`\d+\.\d+`);

const lines = "C:\\logs\n"; // has another escape
const folder = "C:\\logs\\"; // ends with a backslash