JavaScript: substring() vs substr()
What is the difference between substring()
and substr()
?#
Quick tip for remembering the difference:
substring
- index-basedsubstr
- 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';
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.
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.