TypeScript: Prefer slice() over substring()

I would like to propose the following rule:

Prefer slice() over substring()

In ECMA String.prototype.sliceand String.prototype.substring are defined to perform the same operation on a string instance. The difference in behavior only exists when the arguments provided (start and end), are not provided as numbers, or when start is bigger than end, in which slice() does not try to be forgiving, which is considered a good thing.

Non-compliant

function getCountry(iban: string): string {
    return iban.substring(0, 2);
}

Compliant

function getCountry(iban: string): string {
    return iban.slice(0, 2);
}

See: javascript - What is the difference between String.slice and String.substring? - Stack Overflow

2 Likes

Hello @Corniel,

I created a ticket to consider this idea for a rule.

I agree with you that slice is a better solution overall as it behaves as one would expect, but we need to consider also if raising an issue for every String.prototype.substring() usage would be too noisy for our users.

Cheers,
Victor

1 Like

Good luck with making that decision. With a code fix in place, it might become less of a burden I guess?!

1 Like