There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
The slice() Method
slice()
extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
This example slices out a portion of a string from position 7 to position 12 (13-1):
Example
var res = str.slice(7, 13);
The result of res will be:
Banana
Remember: JavaScript counts positions from zero. First position is 0.
If a parameter is negative, the position is counted from the end of the string.
This example slices out a portion of a string from position -12 to position -6:
Example
var res = str.slice(-12, -6);
The result of res will be:
Banana
If you omit the second parameter, the method will slice out the rest of the string:
Example
or, counting from the end:
Example
The substring() Method
substring()
is similar to slice()
.
The difference is that substring()
cannot accept negative indexes.
Example
var res = str.substring(7, 13);
The result of res will be:
Banana
If you omit the second parameter,
substring()
will slice out the rest of the string.The substr() Method
substr()
is similar to slice()
.
The difference is that the second parameter specifies the length of the extracted part.
Example
var res = str.substr(7, 6);
The result of res will be:
Banana
If you omit the second parameter, substr()
will slice out the rest of the string.
Example
var res = str.substr(7);
The result of res will be:
Banana, Kiwi
If the first parameter is negative, the position counts from the end of the string.
Example
var res = str.substr(-4);
The result of res will be:
Kiwi
Practice Excercise Practice now