Emmanuel Akinfulubi

JavaScriptFunction

Function to count vowels in a string in JavaScript

Beginner · 3 min read

Counting the vowels in a sentence is one of the first string exercises most people meet. 'The quick brown fox' has five: e, u, i, o, o. The exercise also says that y does not count. The same kind of counting powers readability scores, word games and simple text statistics.

In this tutorial you will write a one-line function called countVowels using a regular expression. You will see why it needs a strange ?? [] at the end, write a loop version to compare, and find out what happens with accented letters like the é in café. You need to know what a function and a string are.

A regular expression in one minute

A regular expression, or regex, is a pattern for finding text. It is written between two slashes. [aeiou] means "any one of the letters a, e, i, o or u". Letters after the closing slash are flags that change how it searches:

  • g (global) finds every match, not just the first.
  • i (ignore case) treats capitals and small letters as the same, so A matches too.

match runs the pattern on a string and returns an array of every match:

JavaScript

console.log('banana'.match(/[aeiou]/gi)); // [ 'a', 'a', 'a' ]

The number of vowels is the length of that array.

Here is the exercise. Try it yourself first if you like, or read on and we will build it together.

7 Count the vowels

easy

'The quick brown fox' should give 5. The question is explicit that y does not count.

Stuck? Three hints, smallest first
  1. 1. match(/[aeiou]/gi) returns null when there are none, not an empty array.
  2. 2. The i flag handles capitals, so A counts as well as a.
  3. 3. Accented vowels are not in [aeiou], so café counts two, not three.

Step 1: match and count

Step 1

console.log('The quick brown fox'.match(/[aeiou]/gi).length); // 5

That is the right answer for the example. Now try a word with no vowels at all.

Step 2: the null trap

Step 2

console.log('rhythm'.match(/[aeiou]/gi)); // null

When nothing matches, match returns null, not an empty array. And null.length throws a TypeError, so the one-liner from Step 1 crashes on 'rhythm'.

The fix is ??, the nullish coalescing operator. a ?? b gives a, unless a is null or undefined, in which case it gives b. So ?? [] swaps a null for an empty array, which has length 0:

Step 2b

const countVowels = (text) => (text.match(/[aeiou]/gi) ?? []).length;
console.log(countVowels('The quick brown fox')); // 5
console.log(countVowels('rhythm'));              // 0
console.log(countVowels('AEIOU'));               // 5

The brackets around text.match(...) ?? [] matter: they make sure .length is read from the result of ??, not from [] alone.

Step 3: the same thing with a loop

A loop version makes each step visible. for...of walks through a string one character at a time, and includes checks whether a character is in 'aeiou':

Step 3

const countByLoop = (text) => {
  let n = 0;
  for (const c of text.toLowerCase()) if ('aeiou'.includes(c)) n++;
  return n;
};
console.log(countByLoop('The quick brown fox')); // 5
console.log(countByLoop(''));                    // 0

toLowerCase() does the job the i flag did in the regex. Both versions give the same answers, and the loop has no null to worry about.

Step 4: accented vowels

[aeiou] only knows the five plain English vowels. A person reading "café" sees two vowels, a and é. The regex sees one:

Step 4

console.log(countVowels('caf\u00e9')); // 1

\u00e9 is the character é written as a code, so the snippet is easy to copy. To count it, you can split each accented letter into a plain letter plus a separate accent mark, then delete the marks. normalize('NFD') does the splitting. The accent marks all live in the range of codes \u0300 to \u036f, so a regex can remove them:

Step 4b

const countVowelsAccented = (text) =>
  (text.normalize('NFD').replace(/[\u0300-\u036f]/g, '').match(/[aeiou]/gi) ?? []).length;
console.log(countVowelsAccented('caf\u00e9'));     // 2
console.log(countVowelsAccented('na\u00efve'));    // 3
console.log(countVowelsAccented('\u00c9tienne')); // 4

After that, é has become a plain e, and the usual pattern counts it. "Naïve" and "Étienne" work the same way.

The full solution

The panel has all three: countVowels, countByLoop and countVowelsAccented. It prints the example, 'rhythm', the capitals, then three accented words counted both ways, and finally the null that match returns when there are no vowels. Press Run to see the output.

The answer

const countVowels = (text) => (text.match(/[aeiou]/gi) ?? []).length;

// No regex, for comparison.
const countByLoop = (text) => {
  let n = 0;
  for (const c of text.toLowerCase()) if ('aeiou'.includes(c)) n++;
  return n;
};

// Accented vowels included, by stripping the accents first.
const countVowelsAccented = (text) =>
  (text.normalize('NFD').replace(/[\u0300-\u036f]/g, '').match(/[aeiou]/gi) ?? []).length;

console.log("countVowels('The quick brown fox') =", countVowels('The quick brown fox'));
console.log('the expected value                =  5');
console.log("y is not counted: 'rhythm' ->", countVowels('rhythm'));
console.log("'AEIOU' ->", countVowels('AEIOU'), '(the i flag)');
console.log("--- accents ---");
console.log("'caf\u00e9'    plain:", countVowels('caf\u00e9'), ' accent-aware:', countVowelsAccented('caf\u00e9'), '<- the \u00e9 is missed');
console.log("'\u00c9tienne' plain:", countVowels('\u00c9tienne'), ' accent-aware:', countVowelsAccented('\u00c9tienne'));
console.log("'na\u00efve'   plain:", countVowels('na\u00efve'), ' accent-aware:', countVowelsAccented('na\u00efve'));
console.log("match on no vowels returns", 'rhythm'.match(/[aeiou]/gi), '<- null, not []');

Output


      
17 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 17 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

17 checks

test("the example in the question", countVowels('The quick brown fox'), 5);
test('capitals count', countVowels('AEIOU'), 5);
test('and lower case', countVowels('aeiou'), 5);
test('y is not a vowel here', countVowels('rhythm'), 0);
test('nor in "y" alone', countVowels('y'), 0);
test('an empty string counts 0', countVowels(''), 0);
test('a string with no vowels does not crash', countVowels('xyz'), 0);
test('because match returns null there', 'xyz'.match(/[aeiou]/gi), null);
test('the loop version agrees', ['The quick brown fox', 'rhythm', 'AEIOU', ''].every((t) => countVowels(t) === countByLoop(t)), true);
test('caf\u00e9 has two vowels to a person', countVowelsAccented('caf\u00e9'), 2);
test('but [aeiou] finds only one, missing the \u00e9', countVowels('caf\u00e9'), 1);
test('so the two disagree', countVowels('caf\u00e9') === countVowelsAccented('caf\u00e9'), false);
test('na\u00efve has three vowels', countVowelsAccented('na\u00efve'), 3);
test('and [aeiou] finds two', countVowels('na\u00efve'), 2);
test('an accented capital counts once accents are stripped', countVowelsAccented('\u00c9tienne'), 4);
test('while [aeiou] misses the \u00c9', countVowels('\u00c9tienne'), 3);
test('spaces and punctuation are ignored either way', countVowels('a e, i!'), 3);

Two recurring details. match with the g flag returns null rather than an empty array when nothing matches, so ?? [] before .length is not optional — the assertion checks the null directly so the reason is on the page.

And [aeiou] is an English assumption. café counts two vowels by that rule and three by any reasonable human reading, which the assertions state as a disagreement rather than picking a side. The fix is normalize('NFD') to split each accented character into a base letter plus a combining mark, then remove the marks — the same normalisation trick that turns up whenever text has to be compared or measured.

Common mistakes

  • Reading .length straight off match. When there are no vowels, match returns null and the code crashes. Add ?? [].
  • Forgetting the i flag. Without it, capital vowels like the A in "Abuja" are not counted.
  • Forgetting the g flag. Without it, match stops at the first vowel and returns a different kind of array, so the count is wrong.

Try it yourself

  1. Write countConsonants(text). Count letters that are not vowels, and make sure spaces and punctuation don't count.
  2. Change countVowels so y counts as a vowel too, and test 'rhythm' again.
  3. Return how many times each vowel appears, as an object like { a: 1, e: 2 }.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.