Skip to content

Latest commit

Β 

History

History
54 lines (37 loc) Β· 2.1 KB

File metadata and controls

54 lines (37 loc) Β· 2.1 KB

prefer-split-limit

πŸ“ Prefer String#split() with a limit.

πŸ’Ό This rule is enabled in the following configs: βœ… recommended, β˜‘οΈ unopinionated.

πŸ”§ This rule is automatically fixable by the --fix CLI option.

When you only need a prefix of the results from splitting a string, pass a limit to String#split(). This can improve performance by allowing the method to stop once enough parts have been produced, and it makes your intent clearer.

This rule checks two patterns with a non-empty string literal or regular expression literal separator: direct array destructuring in a variable declaration or standalone assignment expression, and direct access using a statically known non-negative integer index.

Examples

// ❌ - Splits entire string, then accesses index 0
const protocol = url.split(':')[0]; // Could be long URL

// βœ… - Splits into at most one part
const protocol = url.split(':', 1)[0]; // More efficient
// ❌ - Gets second part from full split
const [, filename] = path.split('/');

// βœ… - Splits into at most two parts while preserving the destructuring
const [, filename] = path.split('/', 2);
// ❌
const part = csvLine.split(',')[3];

// βœ… - Limit is the index plus one so the element can be produced
const part = csvLine.split(',', 4)[3];
// βœ… - Accessing negative index (needs full array)
const lastPart = string.split('/').at(-1);

// βœ… - Unknown separator or index
const parts = string.split(dynamicSeparator)[unknownIndex];

// βœ… - The rest element needs all remaining parts
const [firstPart, ...remainingParts] = string.split('/');

Note

Performance benefits depend on the JavaScript engine. The main benefit is clearer intent showing you only need specific parts.