The difference between the
indexEnd. It returns the portion of the string that starts at
indexStart and ends the character immediately preceding
indexEnd. For example:
const str = 'Twas the night before Christmas'; let indexStart = 0; let indexEnd = 4; str.substring(indexStart, indexEnd); // 'Twas' str.substring(5, 14); // 'the night'
If you don't specify
substring() function returns the rest of the string starting at
str.substring(5); // 'the night before Christmas'
substring() function has some quirky behavior in edge cases:
indexEndis less than 0, it is treated as 0.
indexEnd < indexStart, the two are swapped.
substring(4, -1) is equivalent to
substring(4, 0), which in turn is equivalent to
substring(0, 4) as shown below.
str.substring(4, -1); // 'Twas'
The key difference between
substr() is that
substr() has a different 2nd parameter. The first parameter to
start, and the 2nd is
length. For example:
const str = 'Twas the night before Christmas'; let start = 0; let length = 4; // If `start === 0`, `substr()` and `substring()` are equivalent str.substr(start, length); // 'Twas' str.substr(5, 9); // 'the night' 'the night'.length; // 9
substring(), you can call
substr() with a negative
start. That will make
substr() start counting at the end of the string as opposed to the beginning. For example:
const str = 'Twas the night before Christmas'; let start = -9; let length = 9; str.substr(start, length); // 'Christmas' 'Christmas'.length; // 9
slice() function is less common than
substr(). However, it has the best aspects of both
slice() function takes the start and end indices as parameters, and is not considered a legacy function. Like
slice() function supports negative indices. For example:
const str = 'Twas the night before Christmas'; str.slice(0, 4); // Twas str.slice(5, 14); // the night str.slice(-16, -10); // before str.slice(-9); // Christmas
slice() function seems like the clear winner out of the 3:
- Not considered a "legacy function"
- Supports negative indices
- Less name confusion: there's no