What is the difference between substring() and substr()?#

Quick tip for remembering the difference:

  • substring - index-based
  • substr - length-based

Both substring() and substr() accept an index-based first parameter, but the second parameter of substring() is index-based (the end index), while the second parameter of substr() length-based (number of characters to return).

Under most conditions, both behave very similarly. Take a look at these examples.

const name = 'hippopotamus';
Run
Clear
Run
Clear
Run
Clear
Run
Clear

The difference becomes obvious when both the parameters are specified and the starting index is a positive integer, and the end index is within the length of the string.

Run
Clear
Run
Clear
Run
Clear

substr() is considered "legacy", so you might as well forget about its existence . Always prefer to use substring() over substr().

Summary#

substring() returns the characters of a string from a starting index to an end index, substr() on the other hand, returns an n number of characters from a starting index.

References#

  1. MDN - substring
  2. MDN - substr
Tweet this | Share on LinkedIn |