String slicing allows you to extract a portion of a string.
It takes two parameters: the starting index and the ending index (optional). It returns a new string containing the extracted portion.
Let's perform such operations on the string "computer". It's structure is the following:
Output:
In this example str.slice(3)
skips the first 3
symbols of the string - c
, o
and m
.
The other part of the string (starting from the 3rd index - p
) is extracted - puter
.
Negative indexes track the string characters in reverse.
Output:
In this example str.slice(-3)
extracts only the last 3 symbols of the string - t
, e
and r
.
Output:
In this example str.slice(3, 5)
skips the first 3
symbols of the string - c
, o
and m
.
Afterwards it takes the rest of the string until it reaches the 5th symbol - u
.
Output:
In this example str.slice(-5, -2)
starts slicing at 5th symbol counting backwards and ends before the second symbol counting backwards.
Both positive and negative arguments can be specified.
Output:
In this example str.slice(1, -1)
starts after the first symbol and ends before the last symbol.
An invalid case simply returns an empty string. In such cases the slicing start argument position is after the slicing end.
Example of valid and invalid case:
Output:
Another invalid slicing case is specifying starting argument that's beyound the string's bounds:
Output: