The main differences between
substr() methods are as follows:
- They have different second arguments;
- Negative starting index has a different meaning in both;
- They have differences in return values if start index is greater.
Please note that the
substr() method is considered a legacy feature in ECMAScript and might be removed in future versions. Therefore, it is best to avoid using it whenever possible.
Different Second Arguments
They both have a different second argument:
substring(startIndex[, endIndex]): takes the starting index as the first argument and an optional end index as the second argument;
substr(startIndex[, length]): takes the starting index as the first argument and an optional second argument to specify the number of characters to extract after the start index.
To illustrate these differences, let's consider the following examples:
'foobar'.substring(3, 6); // output: 'bar' 'foobar'.substr(3, 3); // output: 'bar' 'foobar'.substring(1, 3); // output: 'oo' 'foobar'.substr(1, 2); // output: 'oo'
Using Negative Indexes as the Start Index
- If the start index of
substring()is a negative number, then it is ignored and treated as
- If the start index of
substr()is a negative number, then the index starts counting from the end of the string (and its value is capped at
'foobar'.substring(-3, 3); // output: 'foo' 'foobar'.substr(-3, 3); // output: 'bar' 'foobar'.substring(-3); // output: 'foobar' 'foobar'.substr(-3); // output: 'bar'
If the second argument is negative for either of the methods, it is treated as
Handling of Start Index Being Greater
Both methods handle the start index (i.e. the first argument) being greater than the second argument differently:
substring(), if the start index is greater than the end index, then it is treated as if the two arguments were swapped;
substr(), since the second argument is the number of characters to extract after the start index, it does not matter if the start index is greater or lesser than the second argument.
'foobar'.substring(3, 0); // output: 'foo' 'foobar'.substr(3, 0); // output: '' 'foobar'.substring(3, 1); // output: 'oo' 'foobar'.substr(3, 1); // output: 'b' 'foobar'.substring(3, 3); // output: '' 'foobar'.substr(3, 3); // output: 'bar'
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.