substring and slice
- Node.js course
- Beginner
- Lesson 32/116
- 5 min
Learn to take parts of a string with .substring and .slice.
Taking parts with substring
To take a part of a string you use .substring(start, end). start is the start index and end is the end index; end itself is excluded. "welcome".substring(0, 3) returns "wel".
With one argument substring(start) takes from that index to the end: "welcome".substring(3) is "come". substring clamps negative indices to zero; for negative values slice is usually a better fit.
slice and negative indices
.slice(start, end) also takes a part; it resembles substring but supports negative indices. A negative index counts from the end: -1 is the last character, -3 is the start of the last three characters.
For example "welcome".slice(-3) returns the last three letters: "ome". "welcome".slice(0, -2) drops the last two characters: "welc". Thanks to its flexibility slice is a common choice for strings and arrays.
Practice Take the first three letters
The word variable holds "programming". Declare a variable first and assign the result of word.slice(0, 3) to it. Then print first with console.log. The output on a single line must be pro.
Starter code
const word = "programming";
// Declare first with slice and print itSample solution
const word = "programming";
const first = word.slice(0, 3);
console.log(first);Expected output
pro
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Write the substring call
const w = "welcome";
const head = w____(0, 3);
const w = "welcome";
const head = w.substring(0, 3);
Explanation: .substring takes two indices and returns a part.
2 Match each method to its behavior
| Term | Meaning |
|---|---|
.substring(0, 3) |
First three chars |
.slice(-3) |
Last three chars |
.substring(3) |
From index to end |
.slice(0, -2) |
Drop last two |
3 What is the result of "welcome".slice(-2)?
"welcome".slice(-2)- "me" Correct answer
- "wel"
- "come"
- "welc"
Explanation: slice(-2) gives the last two characters: "me".