JavaScript substring vs substr vs slice Explained

JavaScript provides three distinct methods for extracting sections of a string: slice(), substring(), and substr(). While all three serve a similar purpose, they differ fundamentally in how they interpret arguments, handle negative values, and adhere to modern web standards. This guide breaks down the syntax, differences, and best practices for each method so you can determine the right one to use.

Quick Syntax Comparison


1. slice(startIndex, endIndex)

The slice() method is the standard and most flexible tool for string extraction in modern JavaScript.

const str = "JavaScript";

// Basic extraction
str.slice(0, 4);   // "Java"

// Using negative index
str.slice(-6);     // "Script"
str.slice(0, -6);  // "Java"

// Start greater than end
str.slice(4, 0);   // ""

2. substring(startIndex, endIndex)

The substring() method is similar to slice(), but it handles edge cases differently.

const str = "JavaScript";

// Basic extraction
str.substring(0, 4);   // "Java"

// Negative indices treated as 0
str.substring(-6);     // "JavaScript" (interprets as str.substring(0))
str.substring(4, -2);  // "Java" (swaps to (0, 4))

// Automatic swapping when start > end
str.substring(4, 0);   // "Java" (swaps to (0, 4))

3. substr(startIndex, length)

The substr() method differs from the other two because its second argument specifies the total number of characters to extract, rather than an end position.

const str = "JavaScript";

// Extract by length
str.substr(0, 4);   // "Java"
str.substr(4, 6);   // "Script"

// Negative starting point
str.substr(-6, 3);  // "Scr"

Summary of Key Differences

Feature slice() substring() substr()
Second Parameter End Index End Index Length
Negative Arguments Counts from end Treated as 0 Start can be negative
start > end Handling Returns "" Swaps arguments Not applicable
ECMAScript Status Standard Standard Deprecated (Legacy)

Recommendation

Use slice() for general string slicing because it behaves predictably, works identically to Array.prototype.slice(), and correctly handles negative index positioning. Avoid using substr() in new code.