Emmanuel Akinfulubi

JavaScriptString

Count vowels, including accented letters, in JavaScript

Beginner · 3 min read

Counting vowels is a classic first string exercise. It teaches you how to find every match of a pattern and count them. It also hides a trap: the usual answer crashes on a word with no vowels, and miscounts words with accents like 'café'.

In this tutorial you will write countVowels, make it safe for words like 'rhythm', and then see why 'café' gives 1 instead of 2 and how to fix it. You should know what a string and a function are. The regular expression parts are explained below.

A pattern for vowels

In a regular expression, square brackets make a character class: [aeiou] matches any one of the letters inside. After the closing slash you can add flags:

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

What match returns

text.match(/[aeiou]/gi) returns an array of every vowel it finds. So its length is the count. But when there are no matches, match doesn't return an empty array. It returns null, which means "nothing". And null has no length.

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

36 Count the vowels

easy

Count the vowels in a word, ignoring case. Then try it on 'café' and explain the answer.

Stuck? Three hints, smallest first
  1. 1. match with the g and i flags gives every vowel.
  2. 2. match returns null rather than an empty array when nothing matches.
  3. 3. An accented vowel is not in [aeiou], but it is after normalize(‘NFD’).

Step 1: find the vowels

Step 1

console.log('lagos'.match(/[aeiou]/gi));        // [ 'a', 'o' ]
console.log('lagos'.match(/[aeiou]/gi).length); // 2

Two vowels, a and o.

Step 2: a word with no vowels

Step 2

console.log('rhythm'.match(/[aeiou]/gi)); // null
try {
  console.log('rhythm'.match(/[aeiou]/gi).length);
} catch (e) {
  console.log(e.constructor.name); // 'TypeError'
}

match returned null, and reading .length of null throws a TypeError. So the simple version crashes on exactly the words you might be testing it on.

Step 3: fall back to an empty array

|| gives the right side when the left side is a "falsy" value such as null. So match(...) || [] means "the matches, or an empty array if there were none":

Step 3

const countVowels = (text) => (text.match(/[aeiou]/gi) || []).length;
console.log(countVowels('lagos'));  // 2
console.log(countVowels('LAGOS'));  // 2
console.log(countVowels('rhythm')); // 0
console.log(countVowels(''));       // 0

Thanks to the i flag, capitals are counted. A word with no vowels gives 0, and so does an empty string. (text.match(re) || []).length is a pattern worth remembering for any "count the matches" job.

Step 4: a few more checks

Step 4

const countVowels = (text) => (text.match(/[aeiou]/gi) || []).length;
console.log(countVowels('sky'));                 // 0
console.log(countVowels('aeiou'));               // 5
console.log(countVowels('the quick brown fox')); // 5

y is not in our class, so 'sky' has none. That is a choice: add y to the class if you want it counted.

Step 5: an accented letter

Step 5

const countVowels = (text) => (text.match(/[aeiou]/gi) || []).length;
console.log(countVowels('café')); // 1

You can see two vowels, a and é. But é is a different character from e, and it isn't in [aeiou]. Only the a is counted. The class quietly assumes plain English letters.

Step 6: split the accent off with normalize

The same letter é can be stored in two ways: as one character, or as a plain e followed by a separate combining accent that sits on top of it. normalize('NFD') turns text into the second form. Then the e is a plain e again and matches the class:

Step 6

const countVowels = (text) => (text.match(/[aeiou]/gi) || []).length;
const word = 'café';
console.log(word.length);                          // 4
console.log(word.normalize('NFD').length);         // 5
console.log(countVowels(word.normalize('NFD')));   // 2

After normalizing, the word is five characters: c, a, f, e and the accent. The accent itself isn't a vowel, so it isn't counted, but the e is. Now 'café' has two vowels. The same trick is behind search boxes that find "cafe" when you type "café".

The full solution

Here is the complete answer: countVowels with the || [] fallback, checks for case, empty input and y, and the 'café' pair before and after normalize('NFD'). Press Run and compare the last two lines.

The answer

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

console.log("countVowels('lagos')  :", countVowels('lagos'));
console.log("'rhythm'.match(...)   :", 'rhythm'.match(/[aeiou]/gi), '<- null, hence the || []');
console.log("countVowels('café')   :", countVowels('café'), '<- é is not in the class');
console.log("after NFD             :", countVowels('café'.normalize('NFD')), '<- now it is an e plus a mark');

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.

10 checks

test('a short word', countVowels('lagos'), 2);
test('the i flag makes it case-insensitive', countVowels('LAGOS'), 2);
test('no vowels gives zero, not null', countVowels('rhythm'), 0);
test('match itself returns null, which is why the default is there', 'rhythm'.match(/[aeiou]/gi), null);
test('an empty string has none', countVowels(''), 0);
test('y is not counted here', countVowels('sky'), 0);
test('a vowel-only string counts every letter', countVowels('aeiou'), 5);
test('a sentence', countVowels('the quick brown fox'), 5);
test('an accented vowel is NOT in the character class', countVowels('café'), 1);
test('decomposing first separates the e from its accent', countVowels('café'.normalize('NFD')), 2);

(text.match(re) || []).length is the idiom worth memorising. match with g returns null for no matches rather than [], so counting without the default throws on exactly the input you were counting for.

The 'café' pair is the useful bit. [aeiou] is an ASCII assumption hiding inside a task that sounds language-neutral. normalize('NFD') splits é into e plus a combining accent, at which point the e matches — which is also the trick behind accent-insensitive search, in exercise 44.

Common mistakes

  • Reading .length straight off match. It throws on text with no matches. Use (text.match(re) || []).length.
  • Forgetting the g flag. Without it, match returns only the first vowel (with some extra details), so the count is wrong.
  • Assuming [aeiou] covers every vowel. Accented letters are separate characters. Normalize with 'NFD' first.

Try it yourself

  1. Write countConsonants(text) that counts letters that are not vowels.
  2. Count the vowels in 'Ọ̀ṣun' with and without normalize('NFD'). What changes?
  3. Return the vowels found, without repeats, so 'banana' gives ['a'].

Keep practising

Newsletter

New writing, when it lands.

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