slice() vs substring() in JavaScript
Intermediate · 3 min read
JavaScript has two methods that cut a piece out of a string, slice and substring. They look the same, they take the same two numbers, and for everyday calls they give the same result. So why are there two, and does it matter which you use?
It does. In this tutorial you will call both with the same arguments and find the two cases where they disagree: when the numbers are the wrong way round, and when they are negative. Once you have seen those, you will know which one to reach for. You should know how slice(start, end) works: the start is included and the end is left out.
A quick reminder of slice
slice(start, end) gives you the characters from start up to, but not including, end. A negative number counts from the right: in a 10-character string, -3 means position 7.
console.log('JavaScript'.slice(0, 4)); // 'Java'
console.log('JavaScript'.slice(-3)); // 'ipt'
substring(start, end) also includes the start and leaves out the end. The difference is what each one does with numbers that don't fit that pattern.
Here is the exercise. Try it on your own first if you like, or read on and we will work through it together.
6 slice against substring
fairCall slice and substring with the same arguments and find the two cases where they disagree: reversed arguments, and negative ones.
Stuck? Three hints, smallest first
- 1. On ordinary, ascending, non-negative arguments they are identical.
- 2.
substringswaps its arguments if the first is larger than the second. - 3.
substringclamps a negative index to 0, whereslicecounts from the right.
Step 1: where they agree
Start with ordinary arguments: two positive numbers, the smaller first.
const text = 'JavaScript';
console.log(text.slice(0, 4)); // 'Java'
console.log(text.substring(0, 4)); // 'Java'
console.log(text.substring(2) === text.slice(2)); // true
Same result, and the same with a single argument. Both also stop at the end of the string if the end number is too big: slice(4, 99) and substring(4, 99) both give 'Script'.
Step 2: put the numbers the wrong way round
Now give the bigger number first.
const text = 'JavaScript';
console.log(JSON.stringify(text.slice(4, 0))); // "", an empty string
console.log(JSON.stringify(text.substring(4, 0))); // "Java"
slice(4, 0) returns an empty string: from position 4 back to position 0 is not a range, so there is nothing to give. substring does something different. When the first number is bigger, it quietly swaps them, so substring(4, 0) becomes substring(0, 4) and returns 'Java'. JSON.stringify only makes the empty string visible when printed.
Step 3: why the swap is dangerous
Swapping sounds helpful. Here is why it isn't. Imagine you meant to cut out a word, but your sum for the end position came out too small:
const text = 'JavaScript';
const start = 4;
const end = start - 3; // a bug: this should have been start + 3
console.log(JSON.stringify(text.slice(start, end))); // "", an empty string
console.log(JSON.stringify(text.substring(start, end))); // "ava"
With slice, the bug shows up straight away as an empty result. With substring, you get 'ava', text that looks reasonable, so the mistake can go unnoticed for a long time.
Step 4: try negative numbers
slice reads a negative number from the right. substring doesn't support negatives at all: it treats any negative number as 0.
const text = 'JavaScript';
console.log(text.slice(-3)); // 'ipt'
console.log(text.substring(-3)); // 'JavaScript'
substring(-3) becomes substring(0), so you get the whole string back instead of the last three characters. The word for this is clamping: pushing a number that is out of range back to the nearest allowed value.
Step 5: two negative numbers
Put the two effects together and the gap gets wider.
const text = 'JavaScript';
console.log(text.slice(-6, -3)); // 'Scr'
console.log(JSON.stringify(text.substring(-6, -3))); // "", an empty string
slice(-6, -3) means slice(4, 7), a real range. substring clamps both to 0, so it becomes substring(0, 0), which is empty.
Step 6: neither one changes the original
const text = 'JavaScript';
text.slice(0, 4);
text.substring(0, 4);
console.log(text); // 'JavaScript'
Both return a new string. Strings in JavaScript can never be changed once they are made.
The full solution
Here is the complete answer, with each disagreement printed next to its slice twin. Press Run and read the lines marked with arrows.
const text = 'JavaScript';
// Same call, two answers, twice.
console.log('slice(4, 0) :', JSON.stringify(text.slice(4, 0)));
console.log('substring(4, 0) :', JSON.stringify(text.substring(4, 0)), '<- arguments silently swapped');
console.log('slice(-3) :', text.slice(-3));
console.log('substring(-3) :', text.substring(-3), '<- negative clamped to 0');
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('they agree on ordinary arguments', text.slice(0, 4), text.substring(0, 4));
test('slice with the arguments reversed returns nothing', text.slice(4, 0), '');
test('substring silently SWAPS them instead', text.substring(4, 0), 'Java');
test('slice reads a negative index from the right', text.slice(-3), 'ipt');
test('substring clamps it to zero, so it returns everything', text.substring(-3), 'JavaScript');
test('two negatives collapse to an empty range in substring', text.substring(-6, -3), '');
test('while slice reads them as a real range', text.slice(-6, -3), 'Scr');
test('both clamp an end past the length', text.slice(4, 99), text.substring(4, 99));
test('and both agree with one non-negative argument', text.substring(2), text.slice(2));
test('neither touches the original', text, 'JavaScript');
The swap is the dangerous one. substring(a, b) where a > b returns a non-empty string, so a subtraction that came out backwards produces plausible-looking output instead of nothing, and the bug survives review. slice returns '' and the mistake shows up immediately.
Use slice. The only reason to know substring is to read code that already uses it.
Common mistakes
- Using
substringwith a negative number to count from the end. It is clamped to 0. Useslice(-3). - Relying on
substringto fix arguments in the wrong order. It hides the bug that put them in the wrong order. Fix the sum instead. - Thinking the two are interchangeable. They only match when both numbers are positive and in order. Pick
sliceand stay with it.
Try it yourself
- Predict, then check:
'Lagos'.substring(3, 1)and'Lagos'.slice(3, 1). - Rewrite
text.substring(0, text.length - 2)withsliceand a negative number. - What does
'Lagos'.substring(-2, 2)return? Explain it using clamping.