String Slicing

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:

string-slicing-structure

Single argument slicing

Positive argument slicing

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 argument slicing

Negative indexes track the string characters in reverse.

positive-and-negative-argument-slicing

Output:

In this example str.slice(-3) extracts only the last 3 symbols of the string - t, e and r.

Two arguments slicing

Positive arguments slicing

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.

Negative arguments slicing

Output:

In this example str.slice(-5, -2) starts slicing at 5th symbol counting backwards and ends before the second symbol counting backwards.

Mixed arguments slicing

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.

Invalid cases

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: