Extract part of a string with slice() in JavaScript
Beginner · 3 min read
Cutting a piece out of a string is one of the jobs you will do most often: the first few letters of a name for a preview, the last four digits of a card number, everything after a prefix like 'ID-'. In JavaScript, the tool for all of these is slice.
In this tutorial you will use slice to take the first four characters of 'JavaScript', the last three, and everything after index 4. You will learn the two rules that explain every result slice gives. You only need to know what a string is and that its characters are numbered from 0.
Indexes are the gaps between characters
The easiest way to picture slice is to number the gaps between the characters, rather than the characters themselves:
| J | a | v | a | S | c | r | i | p | t |
0 1 2 3 4 5 6 7 8 9 10
slice(start, end) cuts at gap start and at gap end, and gives you what is in between. So slice(0, 4) cuts at gap 0 and gap 4, and you get 'Java'.
If you think in character positions instead, the same thing reads: start is included, end is left out. Character 4 is S, and slice(0, 4) stops just before it.
Two rules
Everything slice does follows from these:
- The end index is excluded.
- A negative index counts from the right. It means
length + index, so for a 10-character string,-3means7.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
5 Cut a piece out with slice
easyTake the first four characters of 'JavaScript', then the last three, then everything after index 4.
Stuck? Three hints, smallest first
- 1.
slice(start, end)includesstartand excludesend. - 2. Leave the second argument off to run to the end of the string.
- 3. A negative index counts back from the right, so
slice(-3)is the last three.
Step 1: the first four characters
const text = 'JavaScript';
console.log(text.slice(0, 4)); // 'Java'
console.log(text.slice(0, 1)); // 'J'
slice(0, 4) gives characters 0, 1, 2 and 3. The second line proves the end is left out: from 0 up to, but not including, 1 is just 'J'.
A handy side effect: the length of the piece is end - start. 4 - 0 is 4 characters.
Step 2: everything after index 4
Leave the second number off and slice runs to the end of the string.
const text = 'JavaScript';
console.log(text.slice(4)); // 'Script'
This is how you drop a prefix of known length, for example 'ID-1042'.slice(3) gives '1042'.
Step 3: count from the right
To get the last three characters you could work out text.slice(text.length - 3). A negative number does that sum for you.
const text = 'JavaScript';
console.log(text.slice(-3)); // 'ipt'
console.log(text.slice(-6)); // 'Script'
console.log(text.slice(-6, -3)); // 'Scr'
-3 means 10 - 3, which is 7, so slice(-3) is the same as slice(7). Two negatives make a range: slice(-6, -3) is slice(4, 7), which is 'Scr'.
Step 4: the edge cases
Now try some arguments that don't make a normal range.
const text = 'JavaScript';
console.log(text.slice()); // 'JavaScript'
console.log(JSON.stringify(text.slice(50))); // "", an empty string
console.log(JSON.stringify(text.slice(4, 0))); // "", an empty string
With no arguments, slice copies the whole string. A start past the end gives an empty string, because there is nothing after it. And an end that comes before the start also gives an empty string. You might expect slice(4, 0) to give 'Java' backwards, but going from gap 4 to gap 0 isn't a range at all, so there is nothing to return. JSON.stringify is only there so you can see the empty strings when they are printed.
That empty result is useful. If you ever calculate the two numbers the wrong way round, you see nothing, and the bug is obvious.
Step 5: the original never changes
const text = 'JavaScript';
const piece = text.slice(0, 4);
console.log(piece); // 'Java'
console.log(text); // 'JavaScript'
Strings in JavaScript can't be changed once they are made. slice always gives you a new string and leaves the original exactly as it was.
The full solution
Here is the complete answer, with every call from the steps printed one after another. Press Run and match each line to the gap picture at the top.
const text = 'JavaScript';
console.log('slice(0, 4) :', text.slice(0, 4));
console.log('slice(4) :', text.slice(4));
console.log('slice(-3) :', text.slice(-3));
console.log('slice(-6,-3):', text.slice(-6, -3));
console.log('slice(4, 0) :', JSON.stringify(text.slice(4, 0)), '<- end before start, so nothing');
Output
10 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 10 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the first four characters', text.slice(0, 4), 'Java');
test('from index 4 to the end', text.slice(4), 'Script');
test('the end index is excluded', text.slice(0, 1), 'J');
test('a negative start counts from the right', text.slice(-6), 'Script');
test('two negatives make a range', text.slice(-6, -3), 'Scr');
test('the last three characters', text.slice(-3), 'ipt');
test('no arguments copies the whole string', text.slice(), 'JavaScript');
test('a start past the end gives an empty string', text.slice(50), '');
test('an end before the start gives an empty string, not a reversed one', text.slice(4, 0), '');
test('slice never changes the original', text, 'JavaScript');
Two rules cover every case: the end index is exclusive, and a negative index means length + index. Everything else follows, including the empty result from slice(4, 0) — index 4 to index 0 is not a range, so there is nothing to return.
slice is the one to reach for by default. The next exercise shows what substring does with the same arguments, and why the difference is worth knowing rather than discovering.
Common mistakes
- Expecting the end index to be included.
slice(0, 4)is four characters, positions 0 to 3. Add 1 to the end if you want position 4 too. - Passing a length as the second argument.
slice(4, 3)is not "three characters from 4", it is an empty string. Useslice(start, start + count). - Expecting
sliceto change the string. It returns a new one, so store it:const short = text.slice(0, 4).
Try it yourself
- Get
'Script'from'JavaScript'using a negative number. - Write
lastFour(cardNumber)that returns the last four digits of'4111111111111234'. - Write
dropPrefix(text, prefix)that removesprefixfrom the start oftextusingsliceandprefix.length.