Explain Codes LogoExplain Codes Logo

What is the difference between substr and substring?

javascript
string-manipulation
substring-vs-substr
javascript-best-practices
Nikita BarsukovbyNikita Barsukov·Jan 6, 2025
TLDR

In JavaScript, when dealing with strings, substring and substr differ in the interpretation of the second parameter. With substring, the end index should be provided (str.substring(1, 3) will result in oz). However, with substr, instead of the end index, you should provide the substring length as the second argument (str.substr(1, 3) yields ozi). Please note that substr is considered deprecated. Therefore, it's recommended to rely on substring or slice for resilient code.

Nailing down the specifics

To select a portion of a string, you can use either substring or substr, but mind how their parameters work:

  1. substring(startIndex, endIndex) it accepts two indices, starting from startIndex (inclusive) and ending at endIndex (exclusive). If startIndex is more significant than endIndex, they flip. Keep away from negative indices; they're treated as 0.
  2. substr(startIndex, length) it accepts a starting index and the length of the substring to return. Interestingly, if startIndex is negative, it starts from the end of the string. Useful for snapping those tail strings!

Legacy and deprecation - Dusting off old books

substr has a history, but times change, and so does JavaScript. The substr method, while still supported, is considered a relic, and its use is advised against. For the newer, shinier options, look towards substring or slice.

Choosing the right tools for slicing and dicing

When deciding between the methods, consider what's known about the string and what you need:

  • Are the start and end locations specified without uncertainty? substring is the way forward.
  • Need to count from the end of the string? Surprise your mates with substr and negative indices!
  • Worried about your code's consistency across different browsers? Ditch substr for slice. Even Internet Explorer agrees on this!

Pitfalls and solutions - The jungle of code

The choice between substring and substr can indeed impact your code’s readability and reliability. Here’s some quick points to remember:

  • Code tricks: Need a quick string reversal? substr is your 'String Reverso' kit!
  • Gotchas: Swapping parameters with substring not only swaps the coins, but also could bite back as a silent bug.

Future coding styles

Given how substring and slice play together and how slice is quite the powerhouse, it has become a darling among developers for most use cases:

  • Negative indices? slice says 'no problem'!
  • Working across arrays and strings? Count on slice to slice through any challenge.