Count occurrences of a substring in JavaScript
Intermediate · 4 min read
How many times does a word appear in a paragraph? How many commas are in a line of a CSV file? Counting how often one piece of text shows up inside another is a common job, and a classic interview question. It has a twist that catches people out: does aa appear in aaaa two times or three?
In this tutorial you will write two counting functions, countOccurrences and countOverlapping, and see why they give different answers. You'll also guard against an empty search term, which can freeze a browser tab. You need to know what strings, functions and while loops are.
The words we'll use
The text you search in is often called the haystack, and the text you search for is the needle, as in "a needle in a haystack". In the code below, text is the haystack and needle is the needle.
Two tools: split and indexOf
split(needle) cuts the text at every place the needle appears:
console.log('banana'.split('a')); // [ 'b', 'n', 'n', '' ]
indexOf(needle, from) returns the position where the needle is first found, starting the search at from. If it isn't found, you get -1:
console.log('banana'.indexOf('a')); // 1
console.log('banana'.indexOf('a', 2)); // 3
console.log('banana'.indexOf('z')); // -1
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
108 Count how many times one string occurs in another
fairCount the occurrences of a word inside a sentence. Then count aa inside aaaa and decide whether the answer is two or three.
Stuck? Three hints, smallest first
- 1.
text.split(needle).length - 1counts non-overlapping occurrences in one line. - 2. A loop with
indexOf(needle, from)lets you choose how far to jump after a match. - 3. An empty needle has to be refused, or the loop never ends.
Step 1: count with split
Look again at 'banana'.split('a'). It gave four pieces. Cutting a string always makes one more piece than there are cuts (three cuts, four pieces), so the number of matches is the number of pieces minus one:
function countOccurrences(text, needle) {
return text.split(needle).length - 1;
}
console.log(countOccurrences('Lagos to Lagos through Lagos', 'Lagos')); // 3
console.log(countOccurrences('banana', 'a')); // 3
console.log(countOccurrences('banana', 'z')); // 0
When the needle isn't there, split returns one piece, the whole text, so the count is 0.
Step 2: the aa question
function countOccurrences(text, needle) {
return text.split(needle).length - 1;
}
console.log(countOccurrences('aaaa', 'aa')); // 2
split uses up each match. It takes the letters at positions 0 and 1 as the first aa, then carries on from position 2 and takes positions 2 and 3 as the second. But aa also starts at position 1 (the middle two letters). Those overlapping matches share letters, and split never counts them.
So the honest answer is: two if you ask "how many times can I take it out", three if you ask "how many places does it start". Both are valid questions.
Step 3: count by hand with a loop
A loop with indexOf lets you choose how far to move after each match:
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
Each time a match is found at position at, the next search starts at at + 1, one character later. That lets the next match share letters with this one. If you moved on by at + needle.length instead, you'd skip past the whole match and get 2 again.
Step 4: the empty needle
What should counting '' mean? Look at what the code does with it:
console.log('aaaa'.indexOf('')); // 0
console.log('aaaa'.indexOf('', 2)); // 2
console.log('aaaa'.split('').length - 1); // 3
The empty string is found at every position. A loop that moves on by needle.length would move by 0 and never stop, freezing the tab. And the split version would quietly report a count based on the number of characters, which answers a different question.
The fix is one line at the top of each function: if there's no needle, return 0.
function countOccurrences(text, needle) {
if (!needle) return 0;
return text.split(needle).length - 1;
}
console.log(countOccurrences('aaaa', '')); // 0
!needle is true for an empty string, so the function returns before it does any searching.
Step 5: upper and lower case
function countOccurrences(text, needle) {
if (!needle) return 0;
return text.split(needle).length - 1;
}
console.log(countOccurrences('Lagos lagos', 'lagos')); // 1
console.log(countOccurrences('Lagos lagos'.toLowerCase(), 'lagos')); // 2
Counting is case sensitive: 'Lagos' and 'lagos' are different text. Lowercase the haystack first if you want to count both.
The full solution
The answer panel has both functions, each with the empty-needle guard, and checks words, single letters, a missing needle, overlaps, case and the empty needle. Press Run to see the output.
function countOccurrences(text, needle) {
if (!needle) return 0;
return text.split(needle).length - 1;
}
// Same count, done by hand, so the step after a match is visible.
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); // + 1, not + needle.length
}
return count;
}
console.log('aaaa contains aa:', countOccurrences('aaaa', 'aa'), 'non-overlapping,', countOverlapping('aaaa', 'aa'), 'overlapping');
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('a word repeated three times', countOccurrences('Lagos to Lagos through Lagos', 'Lagos'), 3);
test('a single character', countOccurrences('banana', 'a'), 3);
test('something absent counts zero', countOccurrences('banana', 'z'), 0);
test('overlaps are skipped when you jump the whole match', countOccurrences('aaaa', 'aa'), 2);
test('and counted when you jump one character', countOverlapping('aaaa', 'aa'), 3);
test('counting is case sensitive', countOccurrences('Lagos lagos', 'lagos'), 1);
test('lowercase both sides to count either', countOccurrences('Lagos lagos'.toLowerCase(), 'lagos'), 2);
test('an empty needle is refused rather than answered', [countOccurrences('aaaa', ''), countOverlapping('aaaa', '')], [0, 0]);
test('because splitting on it counts characters, which is a different question', 'aaaa'.split('').length - 1, 3);
Two is right for "how many times can I take this out", three is right for "how many places does it appear". The split version answers the first because split consumes each match; the loop answers whichever you choose by how far it advances — at + 1 allows overlaps, at + needle.length forbids them. Neither is the correct answer in general, so pick deliberately and say which in the name.
The empty needle is not a hypothetical. indexOf('', from) matches at every position, so a loop advancing by needle.length never moves and hangs the tab; and split('') returns every character, so the split version reports the string's length as an occurrence count. Guarding at the top gives one honest answer to a meaningless question. Also exercise 25, which tallied every character at once; here a single needle is counted, and the overlap question only exists because it can be more than one character long.
Common mistakes
- Forgetting the
- 1.splitgives one more piece than there are matches. - No guard for an empty needle. A loop can run forever and the split version gives a meaningless count.
- Not deciding about overlaps. Pick one on purpose, and say which in the function's name.
Try it yourself
- Count the commas in
'Ikeja,Yaba,Surulere,Lekki'. How many place names does the line have? - Change
countOverlappingto move on byneedle.lengthand check that it now gives 2 for'aaaa'and'aa'. - Write
countWord(text, word)that ignores case, so'Lagos LAGOS lagos'gives 3.