substr vs substring vs slice
These three methods differ in the parameters, but results in the same primitive string. You can stick to one at all times, or pick the best suited one for each use case.
When passing in a negative value as first parameter they handle it differently:
- substr
Some older interpreters (IE8) will treat a negative start index as 0.
- substring
The smallest value will be used as start index. A negative start index will be treated as 0.
- slice
A negative start index is acceptable, and will start counting from the end.
Performance stats at jsperf.com
The constructors
- String.substr(begin, [length])
Starts from begin position and reads length amonut of characters where stop can not be a negative value.
- String.substring(start, [stop])
Starts from start position and stops at stop position where stop can not be a negative value.
- String.slice(begin, [end])
Starts from begin position and ends at end position where end can be a negative value counting from the end.
Some examples that produce the same result, but have a different set of parameters in the call.
Be aware, all of these can run into issues with multibyte characters.
Comparing to php
Javascript does not have an equal method of php's substr function.
The substr method lets you work with a length parameter, just like php, but will not accept a negative length. For these cases you can use slice.
Example php code
$str = 'Hello World';
$result = substr($str, 3, 2); // lo
$result = substr($str, 1, -2); // ello Wor
$result = substr($str, -5, -2); // Wor
To achieve the same in Javascript you use substr for the first one, and slice for the second one.
You might also want to look at substr function at phpjs.org.