Count overlapping substring matches in JavaScript
Intermediate · 3 min read
How many times does a word appear in some text? You need that for search results ("3 matches"), simple text statistics, or checking that a keyword shows up often enough. It looks like a one-liner, and it nearly is. But there is a question hiding inside it: how many times does 'aa' appear in 'aaaa'? Two, or three?
In this tutorial you will count a word with indexOf in a loop, then write a second version that counts overlapping matches, and see why both answers are right for different questions. You should know what a while loop is. indexOf is explained below.
indexOf with a start position
text.indexOf(needle) returns the position where needle first appears in text, counting from 0. If it isn't there, you get -1.
It takes an optional second argument: where to start looking. That is the key to finding the second, third and later matches.
console.log('the cat sat on the mat'.indexOf('the')); // 0
console.log('the cat sat on the mat'.indexOf('the', 1)); // 15
console.log('the cat sat on the mat'.indexOf('dog')); // -1
Needle and haystack
Programmers often call the text you search in the haystack and the text you search for the needle. This lesson uses text and needle.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
37 Count occurrences of a substring
fairCount how many times 'the' appears in a sentence. Then count 'aa' in 'aaaa' and decide whether the answer is 2 or 3.
Stuck? Three hints, smallest first
- 1. Loop with
indexOfand a start position that moves forward each time. - 2. Advancing by the needle length counts non-overlapping matches; advancing by one counts overlaps.
- 3. An empty needle would loop forever, so refuse it.
Step 1: loop through the matches
Find the first match. While there is one, count it, then look again a little further on:
function countOccurrences(text, needle) {
let count = 0;
let at = text.indexOf(needle);
while (at !== -1) {
count++;
at = text.indexOf(needle, at + needle.length);
}
return count;
}
console.log(countOccurrences('the cat sat on the mat', 'the')); // 2
console.log(countOccurrences('the cat', 'dog')); // 0
at + needle.length starts the next search just past the end of the match we found. When indexOf finally returns -1, the loop stops.
Step 2: the 'aaaa' question
function countOccurrences(text, needle) {
let count = 0;
let at = text.indexOf(needle);
while (at !== -1) {
count++;
at = text.indexOf(needle, at + needle.length);
}
return count;
}
console.log(countOccurrences('aaaa', 'aa')); // 2
It found aa at position 0, jumped to position 2, found aa again, and then there was nothing left. Two matches that don't share any letters. These are non-overlapping matches.
But aa also starts at position 1: the middle two letters. If you are asking "at how many positions does it start?", the answer is 3. Those are overlapping matches.
Step 3: count overlapping matches
To count those, move forward by one position instead of a whole needle:
function countOverlapping(text, needle) {
let count = 0;
let at = text.indexOf(needle);
while (at !== -1) {
count++;
at = text.indexOf(needle, at + 1);
}
return count;
}
console.log(countOverlapping('aaaa', 'aa')); // 3
console.log(countOverlapping('banana', 'ana')); // 2
The only change is at + 1. In 'banana', ana starts at 1 and at 3; they share the middle a.
Neither function is wrong. "How many times could I cut this out?" is 2. "Where does it appear?" is 3. Pick the one your program needs and give the function a name that says which.
Step 4: the shortcuts count non-overlapping
You will often see two shorter ways to count:
console.log('aaaa'.split('aa').length - 1); // 2
console.log(('aaaa'.match(/aa/g) || []).length); // 2
Splitting on the needle gives one more piece than there are matches. A global regex finds every match. Both use up each match before looking for the next one, so both agree with the non-overlapping version. Neither can count overlaps.
Step 5: the empty needle
What if someone searches for an empty string? indexOf('') finds it right where you start looking:
console.log('abc'.indexOf('', 2)); // 2
In the first function, at + needle.length would be at + 0, so the search would find the same position again forever. The loop would never end. So refuse an empty needle at the start:
function countOccurrences(text, needle) {
if (needle === '') return 0;
let count = 0;
let at = text.indexOf(needle);
while (at !== -1) {
count++;
at = text.indexOf(needle, at + needle.length);
}
return count;
}
console.log(countOccurrences('abc', '')); // 0
console.log(countOccurrences('The the', 'the')); // 1
The last line shows the search is case sensitive, so The with a capital isn't counted.
The full solution
Here is the complete answer: both counting functions with the empty-needle guard, plus checks comparing them with the split trick and a global regex. Press Run and compare the two results for 'aa' in 'aaaa'.
function countOccurrences(text, needle) {
if (needle === '') return 0;
let count = 0;
let at = text.indexOf(needle);
while (at !== -1) {
count++;
at = text.indexOf(needle, at + needle.length); // skip past the whole match
}
return count;
}
function countOverlapping(text, needle) {
if (needle === '') return 0;
let count = 0;
let at = text.indexOf(needle);
while (at !== -1) {
count++;
at = text.indexOf(needle, at + 1); // advance one, so overlaps count
}
return count;
}
console.log("'the' in the sentence :", countOccurrences('the cat sat on the mat', 'the'));
console.log("'aa' in 'aaaa', skipping :", countOccurrences('aaaa', 'aa'));
console.log("'aa' in 'aaaa', overlapping :", countOverlapping('aaaa', 'aa'));
console.log('regex with g agrees with the skipping version:', ('aaaa'.match(/aa/g) || []).length);
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('two occurrences in the sentence', countOccurrences('the cat sat on the mat', 'the'), 2);
test('nothing found is zero', countOccurrences('the cat', 'dog'), 0);
test('non-overlapping counting gives 2 for aa in aaaa', countOccurrences('aaaa', 'aa'), 2);
test('counting overlaps gives 3', countOverlapping('aaaa', 'aa'), 3);
test('the split trick agrees with the non-overlapping version', 'aaaa'.split('aa').length - 1, 2);
test('and so does a global regex', ('aaaa'.match(/aa/g) || []).length, 2);
test('so a regex cannot count overlaps either', ('aaaa'.match(/aa/g) || []).length !== countOverlapping('aaaa', 'aa'), true);
test('the empty needle is refused rather than looping forever', countOccurrences('abc', ''), 0);
test('while the split trick would have claimed two', 'abc'.split('').length - 1, 2);
test('counting is case sensitive', countOccurrences('The the', 'the'), 1);
Neither answer for 'aa' in 'aaaa' is wrong; they answer different questions. "How many times could I cut this out?" is 2. "At how many positions does it appear?" is 3. Decide which one your caller wants, and name the function accordingly.
Both the split trick and a global regex count non-overlapping matches, because both consume the match. Overlapping counting needs the manual loop with at + 1, or a lookahead pattern such as /(?=aa)/g.
The empty-needle guard is not defensive padding. indexOf('') returns the start position you gave it, so without the guard at never advances and the loop never ends.
Common mistakes
- No guard for an empty needle. The loop never ends. Return 0 first.
- Expecting
splitor a regex to count overlaps. They count non-overlapping matches only. Use theat + 1loop. - Forgetting case.
'The'and'the'are different. Lowercase both the text and the needle if case shouldn't matter.
Try it yourself
- Make a version that ignores case, so
'The the'gives 2. - Return the positions instead of the count, so
'aaaa'and'aa'give[0, 1, 2]in the overlapping version. - Count how many times
'11'appears in'1111'both ways and explain the two answers.