Extracting Substrings with slice
You'll learn how to pull out specific portions of a string using the slice method with flexible indexing.
What is slice?
The slice method extracts a section of a string and returns it as a new string, without modifying the original. Think of it like cutting a piece from a loaf of bread—the loaf stays intact, but you get a slice to work with.
You call slice with a start index (where to begin cutting) and an optional end index (where to stop, but not including that position). If you omit the end index, slice extracts everything from the start to the end of the string.
Basic Usage
let text = "JavaScript";
let part1 = text.slice(0, 4); // "Java" (from index 0 up to, but not including, 4)
let part2 = text.slice(4); // "Script" (from index 4 to the end)
let part3 = text.slice(4, 10); // "Script" (from 4 up to 10)
Negative Indices
Here's where slice gets really handy: negative numbers count backward from the end of the string. Index -1 is the last character, -2 is second-to-last, and so on.
let word = "hello";
let last3 = word.slice(-3); // "llo" (last 3 characters)
let middle = word.slice(1, -1); // "ell" (from index 1 to 1 before the end)
let lastChar = word.slice(-1); // "o" (just the last character)
This is like saying "give me the last 3 letters" instead of counting from the beginning.
Key Takeaway: Use slice(start, end) to extract substring portions with zero-based indexing; negative indices count backward from the string's end, making it easy to grab characters from the right side without knowing the exact length.