Get all substrings of a string in JavaScript
Intermediate · 3 min read
A substring is a piece of a string made of letters that sit next to each other. 'do' is a substring of 'dog'; so is 'og'. Search boxes, spell checkers and many interview puzzles ("find the longest substring that...") start by looking at every substring of some text.
In this tutorial you will write substrings('dog') and get ["d", "do", "dog", "o", "og", "g"], in exactly that order. You will use two nested loops and slice. You need to know how a for loop works and that string positions start at 0.
Read the expected output first
The order of the answer tells you how to build it. Look at it in groups:
d, do, dog every piece that starts at position 0
o, og every piece that starts at position 1
g the piece that starts at position 2
So the plan is: for each starting position, grow the piece one letter at a time until you reach the end.
Notice what is missing: 'dg'. Its letters are in the right order, but there is a gap where the o should be. A substring never skips letters.
slice(start, end)
text.slice(start, end) copies the letters from start up to, but not including, end:
console.log('dog'.slice(0, 1)); // d
console.log('dog'.slice(0, 3)); // dog
console.log('dog'.slice(1, 3)); // og
Because end is left out, the number of letters you get is end - start.
Here is the exercise. Try it on your own first if you like, or build it with us below.
7 Every substring of a string
fair'dog' should give ["d", "do", "dog", "o", "og", "g"]. Work out from that ordering exactly what is being generated.
Stuck? Three hints, smallest first
- 1. Read the expected output: it is every contiguous run, grouped by starting position.
- 2. Two nested loops — outer for the start, inner for the end.
- 3. This is not the same as a subset or a subsequence.
"dg"is absent for a reason.
Step 1: every piece that starts at 0
Fix start at 0 and let end run from 1 up to the length of the string:
const text = 'dog';
const fromZero = [];
for (let end = 1; end <= text.length; end++) {
fromZero.push(text.slice(0, end));
}
console.log(fromZero); // [ 'd', 'do', 'dog' ]
end starts at 1, not 0, because slice(0, 0) would be an empty string. It goes up to <= text.length so the last slice takes the whole word.
Step 2: let start move too
Now wrap that in a second loop for start. The inner loop begins one past start:
function substrings(text) {
const out = [];
for (let start = 0; start < text.length; start++) {
for (let end = start + 1; end <= text.length; end++) {
out.push(text.slice(start, end));
}
}
return out;
}
console.log(substrings('dog')); // [ 'd', 'do', 'dog', 'o', 'og', 'g' ]
That matches the expected output exactly, order and all. The outer loop picks where a piece begins, and the inner loop picks where it ends.
Step 3: test the small cases
console.log(substrings('a')); // [ 'a' ]
console.log(substrings('ab')); // [ 'a', 'ab', 'b' ]
console.log(substrings('')); // []
An empty string has no starting positions, so the outer loop never runs and you get an empty array.
Step 4: how many are there?
A word with 3 letters gave 6 pieces. Starting at position 0 there are 3 choices of end, at position 1 there are 2, at position 2 there is 1. So the count is 3 + 2 + 1. In general, for n letters it is n(n+1)/2:
console.log(substrings('trip').length, (4 * 5) / 2); // 10 10
console.log(substrings('sixgun').length, (6 * 7) / 2); // 21 21
That number grows fast, so be careful running this on long text.
Step 5: repeated letters repeat pieces
console.log(substrings('aa')); // [ 'a', 'aa', 'a' ]
'a' appears twice because it starts at two different positions. The function lists pieces by position, not unique values. If you want unique ones, put the result in a Set.
Step 6: the thing this is not
These are sometimes called "subsets", but a subset may skip letters, and then 'dg' would be in the list. Lists that keep the order but allow gaps are called subsequences. The answer includes a short version so you can compare:
function subsequences(text) {
if (text.length === 0) return [''];
const [first, ...rest] = text;
const without = subsequences(rest.join(''));
return [...without, ...without.map((s) => first + s)].filter((s) => s !== '');
}
console.log(subsequences('dog').includes('dg')); // true
console.log(substrings('dog').includes('dg')); // false
It calls itself on the rest of the word, then makes every result twice: once without the first letter and once with it. That is a different question with a different answer, so check which one a task really asks for.
The full solution
The panel prints the substrings of 'dog', the subsequences for comparison, and checks the n(n+1)/2 count on longer words. Press Run to see them.
// Every contiguous run, ordered by start then by length. That is exactly the
// ordering the expected output shows.
function substrings(text) {
const out = [];
for (let start = 0; start < text.length; start++) {
for (let end = start + 1; end <= text.length; end++) {
out.push(text.slice(start, end));
}
}
return out;
}
// A subsequence keeps order but allows gaps, so 'dg' IS included. Different
// question, and the expected output rules it out.
function subsequences(text) {
if (text.length === 0) return [''];
const [first, ...rest] = text;
const without = subsequences(rest.join(''));
return [...without, ...without.map((s) => first + s)].filter((s) => s !== '');
}
console.log("substrings('dog') :", substrings('dog'));
console.log("subsequences('dog'):", subsequences('dog').sort(), '<- note "dg"');
console.log('count for a 4-letter word:', substrings('bus').length, 'vs', substrings('trip').length);
console.log('n(n+1)/2 for n=4:', (4 * 5) / 2);
Output
12 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 12 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the expected output, exactly", substrings('dog'), ['d', 'do', 'dog', 'o', 'og', 'g']);
test('a single letter', substrings('a'), ['a']);
test('the empty string gives nothing', substrings(''), []);
test('two letters give three substrings', substrings('ab'), ['a', 'ab', 'b']);
test('the count is n(n+1)/2', substrings('trip').length, (4 * 5) / 2);
test('and for a longer word', substrings('sixgun').length, (6 * 7) / 2);
test('the whole string is always included', substrings('dog').includes('dog'), true);
test('every single letter is included', [...'dog'].every((c) => substrings('dog').includes(c)), true);
test('nothing has a gap in it', substrings('dog').includes('dg'), false);
test('whereas a subsequence does', subsequences('dog').includes('dg'), true);
test('every substring is a real slice of the input', substrings('dog').every((s) => 'dog'.includes(s)), true);
test('duplicated letters produce duplicated substrings', substrings('aa'), ['a', 'aa', 'a']);
These are often called "subsets", which is the wrong word, and the expected output proves it: a subset of the letters of 'dog' would include 'dg', and that is not in the list. What is being asked for is every contiguous substring, which is why two nested loops are enough — there are exactly n(n+1)/2 of them, and the assertions check that count. Both are implemented above so the difference is visible. The last assertion is worth noting too: 'aa' yields 'a' twice, because these are positions, not distinct values.
Common mistakes
- Starting
endatstart.slice(start, start)is an empty string, so you get blanks in the list. - Using
end < text.length. The last letter is never included, and'dog'itself goes missing. - Mixing up substrings and subsequences. If
'dg'should not appear, you want substrings.
Try it yourself
- Change the function so it only returns substrings of length 2:
['do', 'og']. - Return only the unique substrings of
'banana'. (Hint:new Set.) - Find the longest substring of
'abcabcbb'that has no repeated letter, usingsubstringsand a filter.