Both substr
and substring
are common functions to get a sub-string of a given string.
Differences
-
Both methods have two parameters. The first parameters indicate the index of starting position of sub-string. The second parameters are different.
substr(startPosition, length);
substring(startPosition, endPosition);
As you can see, the second parameters of substr
and substring
are the length and the end position of sub-string respectively.
Given a string of helloworld
:
'helloworld'.substr(2, 4);
'helloworld'.substring(2, 4);
-
substr
allows to use a negative number for the start position parameter.
'helloworld'.substr(-2, 4);
substring
, on the other hand, will turn a negative start position to 0 (zero):
'helloworld'.substring(-2, 5);
'helloworld'.substring(0, 5);
Good to know
slice
is another function for getting a sub-string. It's not deprecated as
substr, and supports negative indices.
'helloworld'.slice(2, 4);
'helloworld'.slice(-10, 5);
'helloworld'.slice(-5);