Use slice with negative indexes in JavaScript
Beginner · 4 min read
Cutting a piece out of a string is something you'll do constantly: the first word of an address, the last digit of a code, a file name without its extension. JavaScript has two methods that look like they do the same job, slice and substring. On ordinary input they agree. When the numbers you pass in are negative or the wrong way round, they give very different answers.
In this tutorial you will cut the area name 'Lekki Phase 1' into pieces with slice, then hand both methods the same awkward arguments and compare what comes back. You need to know what a string is and how to call a method on it.
Positions and the excluded end
Every character in a string has a position, called its index, starting from 0:
L e k k i P h a s e 1
0 1 2 3 4 5 6 7 8 9 10 11 12
The space after Lekki is a character too, at index 5. The string has 13 characters, so the last index is 12.
Both slice(start, end) and substring(start, end) take a start and an end. The piece you get includes the start and stops just before the end. So slice(0, 5) gives indexes 0, 1, 2, 3 and 4, which is the five letters of Lekki.
That "end is left out" rule sounds odd at first, but it has a nice side effect: the length of the piece is simply end - start.
What a negative index means
slice also accepts negative numbers. A negative index counts back from the end of the string: -1 is the last character, -3 is the third from the end. substring doesn't understand negatives at all. That one difference causes most of the surprises in this exercise.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
102 slice against substring, and negative indices
easyCut Lekki Phase 1 apart: the first word, the last character, and everything except the last three characters. Then hand slice and substring the same reversed and negative arguments and compare what comes back.
Stuck? Three hints, smallest first
- 1. Both take a start and an end, and both exclude the end.
- 2.
substringswaps arguments that are the wrong way round.slicedoes not. - 3. A negative index counts from the right in
sliceand is clamped to zero insubstring.
Step 1: the first word
const area = 'Lekki Phase 1';
console.log(area.slice(0, 5)); // Lekki
console.log(area.slice(6)); // Phase 1
slice(0, 5) takes indexes 0 to 4. With only one argument, slice(6) starts at index 6 and runs to the end of the string.
Step 2: count from the right
Now the last character, and everything except the last three characters:
const area = 'Lekki Phase 1';
console.log(area.slice(-1)); // 1
console.log(area.slice(0, -3)); // Lekki Phas
slice(-1) starts one from the end, so you get just '1'. In slice(0, -3) the end is three from the right, so the last three characters (e, the space and 1) are cut off. You never had to know the string's length.
Step 3: arguments the wrong way round
In real code, the start and end are often worked out by other code, and sometimes the end comes out smaller than the start. Here is what each method does with 9 and 6:
const area = 'Lekki Phase 1';
console.log(area.slice(9, 6) === ''); // true
console.log(area.substring(9, 6)); // Pha
slice sees an end before the start and gives back an empty string. substring quietly swaps the two numbers, treats it as substring(6, 9), and gives you 'Pha'.
At first substring looks friendlier. It isn't. An empty result is easy to notice. Text from a range you never asked for looks like a correct answer, and that's the kind of bug that slips through.
Step 4: a negative start
const area = 'Lekki Phase 1';
console.log(area.slice(-5)); // ase 1
console.log(area.substring(-5)); // Lekki Phase 1
slice(-5) means "the last five characters", which is the usual way to take the end of a string. substring turns any negative number into 0, so substring(-5) is substring(0), the whole string. Again, no error, just a plausible wrong answer.
Step 5: cutting in two loses nothing
Because the end is left out, cutting at the same index twice splits a string cleanly:
const area = 'Lekki Phase 1';
const before = area.slice(0, 5);
const after = area.slice(5);
console.log(before + after === area); // true
slice(0, 5) stops before index 5 and slice(5) starts at index 5, so every character lands in exactly one half. Nothing is lost and nothing appears twice.
The full solution
The answer panel cuts the area name with slice, then gives both methods the reversed and negative arguments side by side and prints them. The checks cover every case from the steps above. Press Run to see the output.
const area = 'Lekki Phase 1';
const firstWord = area.slice(0, 5);
const lastChar = area.slice(-1);
const withoutLastThree = area.slice(0, -3);
// The same two arguments, the wrong way round, to each method.
const sliceBackwards = area.slice(9, 6);
const substringBackwards = area.substring(9, 6);
// And a negative start to each.
const sliceNegative = area.slice(-5);
const substringNegative = area.substring(-5);
console.log('backwards:', JSON.stringify([sliceBackwards, substringBackwards]));
console.log('negative: ', JSON.stringify([sliceNegative, substringNegative]));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('slice takes a start and an end, end excluded', firstWord, 'Lekki');
test('one argument runs to the end', area.slice(6), 'Phase 1');
test('a negative start counts from the right', lastChar, '1');
test('a negative end trims from the right', withoutLastThree, 'Lekki Phas');
test('slice with the arguments reversed gives nothing', sliceBackwards, '');
test('substring quietly swaps them and gives text', substringBackwards, 'Pha');
test('slice reads a negative start from the right', sliceNegative, 'ase 1');
test('substring clamps it to zero, so you get everything', substringNegative, area);
test('the excluded end means a split at n rejoins exactly', area.slice(0, 5) + area.slice(5), area);
Reach for slice and forget substring exists. They agree on the ordinary case, so the difference only shows up when the arguments are computed and one of them comes out wrong: slice(start, end) with end before start returns '', which is visibly empty, while substring silently reorders them and hands back text from a range you never asked for. That is a bug that survives review.
The negative case is the same story. slice(-5) means "the last five", which is the idiom for a suffix; substring(-5) treats -5 as 0 and returns the whole string, so a clamped-to-zero index looks like success. The last assertion is the property worth remembering: because the end is excluded, slice(0, n) and slice(n) partition a string with nothing lost or duplicated.
Common mistakes
- Thinking the end is included.
area.slice(0, 4)is'Lekk', not'Lekki'. The end index is the first character you don't get. - Using
substringwith a negative number. It doesn't count from the right; it becomes 0. Useslice(-n)for "the last n characters". - Expecting
sliceto change the string. Strings can't be changed in place.slicereturns a new string, so store the result in a variable.
Try it yourself
- Write
extension(fileName)that returns'pdf'for'report.pdf'. (Hint:lastIndexOf('.')tells you where the dot is.) - Use
sliceto get'Phase'out of'Lekki Phase 1'with negative numbers only. - What do
area.slice(20)andarea.slice(-20)give? Predict, then check.