unicorn/prefer-string-slice
Require slice() instead of substr() and substring()
fixable
Three methods cut a string, and each treats its arguments differently. The second argument of substr() is a length, not an end. substring() swaps its arguments if the first is larger and treats a negative number as 0. slice() takes a start and an end, counts negative numbers from the end, and works the same way on arrays.
The rule only looks at the method name, so it reports substr() and substring() on any object.
--fix only renames the method when the result stays the same: substr() with at most one argument, and substring() with non-negative integer literals in ascending order. Rewrite the other calls by hand.
Configure#
Off by default. To turn it on:
bunfig.toml
[lint.rules]
"unicorn/prefer-string-slice" = "error" # or "warn"Examples#
example.js2 problems
const year = date.substringPrefer String#slice() over String#substring()(0, 4);
const month = date.substrPrefer String#slice() over String#substr()(5, 2); // 2 is a lengthexample.jsNo problems
const year = date.slice(0, 4);
const month = date.slice(5, 7); // 7 is the end