Start learning free

LESSON 62 OF 671 · STRINGS I

String Slicing in JavaScript

Lesson

Not only we can select a single character from a string, but we can also select a sequence of consecutive characters (e.g. substring) from a string.

To achieve this, we use the slice() method like this:

string.slice(startIndex, endIndex);

This is called slicing a string. It returns the substring from startIndex to endIndex.

Here is an example:

let language = "JavaScript";
let substring = language.slice(2, 6);

console.log(substring); // Output: "vaSc"
console.log(language); // Output: "JavaScript"

The startIndex is a zero-based index at which we start extraction and the endIndex is also zero-based index before which we end the extraction.

The substring will not include the character at endIndex. You can see in our example that language[2] (v) was included while language[6] (r) was excluded.

Also notice that language preserved its value. The slicing does not affect the original string. It just creates a brand new one representing the sliced substring.


If you omit the endIndex, the slice() extracts to the end of the string:

let language = "JavaScript";
let substring = language.slice(4);

console.log(substring); // Output: "Script"

Assignment
Follow the Coding Tutorial and let's slice some strings!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check