unicorn/prefer-string-starts-ends-with
Require startsWith() and endsWith() instead of a regex with ^ or $
fixable
/^https:/.test(url) asks whether a string starts with some fixed text. url.startsWith("https:") asks the same thing in plain words, and you don't need to escape the text for a regex.
The rule reports .test() on a regex literal that's only ^ followed by plain characters, or plain characters followed by $. A regex with the m flag, or with the i flag and letters, isn't reported.
--fix rewrites the call when the argument is a name, a string, a property access or a call.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/prefer-string-starts-ends-with" = "error" # or "warn"Examples#
example.js2 problems
const secure = /^https:/.testPrefer String#startsWith over a regex with a caret.(url);
const isScript = /\.js$/.testPrefer String#endsWith over a regex with a dollar sign.(file);example.jsNo problems
const secure = url.startsWith("https:");
const isScript = file.endsWith(".js");
const isImage = /\.(png|jpg)$/.test(file);
const isHeader = /^x-/i.test(name);