Course contentsShow
← JavaScript
Lesson 175 of 2,7235. StringsFree lesson

Extracting with substring and substr

Use substring and the legacy substr method to extract string portions, understanding their differences from slice.

Extracting with substring and substr

You'll learn two additional methods for extracting parts of strings and how they differ from slice.

You've already learned slice() for extracting portions of strings. JavaScript also provides substring() and the legacy substr() method. While they accomplish similar goals, their behaviors differ in subtle but important ways.

substring()

The substring() method extracts characters between two indices, just like slice(), but with different rules:

let text = "JavaScript";

text.substring(0, 4);  // "Java" (like slice)
text.substring(4, 10); // "Script"

Key differences from slice:

  • Negative indices are treated as 0 (not counted from the end)
  • Swaps arguments if start > end (automatically corrects order)
text.substring(-3);    // "JavaScript" (treats -3 as 0)
text.substring(4, 0);  // "Java" (swaps to 0, 4)

substr() (Legacy)

The substr() method uses a different signature: substr(start, length) instead of start and end positions.

let word = "Hello";

word.substr(1, 3);  // "ell" (start at 1, take 3 chars)
word.substr(2);     // "llo" (from 2 to end)
word.substr(-3, 2); // "ll" (negative start works!)

Important: substr() is deprecated and should be avoided in new code. Use slice() or substring() instead.

Which Should You Use?

Use slice() as your default choice—it's more predictable and handles negative indices logically. Use substring() only if you specifically need its argument-swapping behavior.

Key Takeaway: substring() extracts between two indices but treats negatives as 0 and swaps reversed arguments; substr() takes a length parameter but is deprecated—stick with slice() for most cases.