The String substring() method
By Flavio Copes
Learn how the JavaScript substring() method returns part of a string and how it differs from slice() by turning any negative argument into 0.
substring() returns a portion of a string and it’s similar to slice(), with some key differences.
You pass it a start index and an optional end index. The character at the end index is not included. With no end index, it goes to the end of the string.
The original string is never modified. Strings in JavaScript are immutable, so you always get a new string back.
How does it handle out-of-range values?
This is where substring() gets opinionated.
If any parameter is negative, it is converted to 0.
If any parameter is higher than the string length, it is converted to the length of the string.
So:
'This is my car'.substring(5) //'is my car'
'This is my car'.substring(5, 10) //'is my'
'This is my car'.substring(5, 200) //'is my car'
'This is my car'.substring(-6) //'This is my car'
'This is my car'.substring(-6, 2) //'Th'
'This is my car'.substring(-6, 200) //'This is my car'
What happens when start is bigger than end?
Here’s the other quirk. If the start index is bigger than the end index, substring() swaps them. slice() returns an empty string instead:
'This is my car'.substring(10, 5) //'is my'
'This is my car'.slice(10, 5) //''
So substring(10, 5) behaves exactly like substring(5, 10). No error, no empty string, it just quietly reorders the arguments.
How is slice() different?
slice() treats negative indexes as counting from the end of the string. That’s often what you want:
'This is my car'.slice(-3) //'car'
'This is my car'.substring(-3) //'This is my car'
That second line is the pitfall to watch for. If you’re used to slice() and pass a negative index to substring(), you don’t get the last characters. The negative value becomes 0 and you get the whole string back. No error, so the bug is easy to miss.
The fix is to use slice() whenever you need to count from the end.
My advice: reach for slice() by default. Its behavior is more predictable, and it does everything substring() does. Knowing how substring() works still matters, because you’ll find it all over existing code.
Related posts about js: