Emmanuel Akinfulubi

JavaScriptBasic

Count the vowels in a string in JavaScript

Beginner · 3 min read

Counting the vowels in a word is one of the first string exercises most people meet. It teaches you how to walk through text one character at a time, and the same pattern counts anything: digits in a password, spaces in a sentence, a letter in a name. In this tutorial you will count vowels two ways and find a trap in the shorter one.

You will write countVowels(text), which returns how many of a, e, i, o and u appear in the text, in either case. Then you will write a one-line version with a regular expression. You need to know what a function and a string are. The rest is explained below.

First, decide what counts

Is "y" a vowel? In "rhythm" it sounds like one; in "yes" it doesn't. There is no single right answer, so the code should say what it decided. Here, y is not counted. Writing that choice in a comment saves the next reader from guessing.

Looping over a string

A for...of loop gives you each character of a string in turn:

JavaScript

for (const ch of 'abc') console.log(ch);

That prints a, then b, then c, each on its own line.

A Set of vowels

A Set is a collection of unique values with a fast has method, which answers "is this value in the set?".

JavaScript

const VOWELS = new Set(['a', 'e', 'i', 'o', 'u']);
console.log(VOWELS.has('e')); // true
console.log(VOWELS.has('x')); // false

Here is the exercise. Try it on your own first if you like, then follow along.

15 Count vowels in a string

easy

Count how many vowels appear in a piece of text.

Stuck? Three hints, smallest first
  1. 1. Decide first whether y counts. Say so in a comment either way.
  2. 2. A Set of vowels makes the check clear and fast.
  3. 3. A regular expression with the g flag plus match is the one-liner, but remember match returns null when nothing matches.

Step 1: count with a loop

Start a counter at 0. For each character, if it is a vowel, add one.

Step 1

const VOWELS = new Set(['a', 'e', 'i', 'o', 'u']); // y is not counted here

function countVowels(text) {
  let n = 0;
  for (const ch of text) {
    if (VOWELS.has(ch)) n++;
  }
  return n;
}
console.log(countVowels('javascript')); // 3
console.log(countVowels('AEIOU'));      // 0

n++ adds one to n. The first test is right: a, a and i. The second is wrong. The set only holds lowercase letters, and 'A' is a different character from 'a'.

Step 2: ignore case

Lowercase the whole text once, before the loop.

Step 2

function countVowels(text) {
  let n = 0;
  for (const ch of text.toLowerCase()) {
    if (VOWELS.has(ch)) n++;
  }
  return n;
}
console.log(countVowels('AEIOU'));             // 5
console.log(countVowels('JavaScript is fun')); // 5
console.log(countVowels('rhythm'));            // 0
console.log(countVowels(''));                  // 0

"rhythm" gives 0, which is correct under our rule that y doesn't count. An empty string also gives 0, because the loop never runs.

Step 3: the one-liner

A regular expression is a pattern for matching text. /[aeiou]/gi matches any one of those five letters. The g flag means "find every match" and the i flag means "ignore case". match returns an array of everything it found.

JavaScript

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

So the count is the length of that array. A first try:

JavaScript

const countVowelsRegex = (text) => text.match(/[aeiou]/gi).length;
console.log(countVowelsRegex('javascript')); // 3
console.log(countVowelsRegex('rhythm'));     // TypeError: Cannot read properties of null (reading 'length')

It crashes on "rhythm". When nothing matches, match returns null, not an empty array, and null has no length.

Step 4: fix the one-liner

?? 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, whose length is 0.

Step 4

function countVowelsRegex(text) {
  return (text.match(/[aeiou]/gi) ?? []).length;
}
console.log(countVowelsRegex('rhythm'));     // 0
console.log(countVowelsRegex('JavaScript')); // 3

The brackets around text.match(...) ?? [] matter: they make sure .length is read after the swap.

The full solution

The complete answer has both versions, counts four samples, and prints what match returns for "rhythm" so you can see the null for yourself. Press Run to see the output.

The answer

const VOWELS = new Set(['a', 'e', 'i', 'o', 'u']);   // y is not counted here

function countVowels(text) {
  let n = 0;
  for (const ch of text.toLowerCase()) {
    if (VOWELS.has(ch)) n++;
  }
  return n;
}

// The one-liner. Note the ?? 0: match returns null, not [], when nothing hits.
function countVowelsRegex(text) {
  return (text.match(/[aeiou]/gi) ?? []).length;
}

const samples = ['javascript', 'JavaScript is fun', 'rhythm', ''];

for (const s of samples) {
  console.log(JSON.stringify(s), '->', countVowels(s));
}

// The trap in the one-liner, made visible:
console.log("'rhythm'.match(/[aeiou]/gi) is", 'rhythm'.match(/[aeiou]/gi));

Output


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

6 checks

test('a mixed word', countVowels('javascript'), 3);
test('a sentence', countVowels('JavaScript is fun'), 5);
test('no vowels at all', countVowels('rhythm'), 0);
test('empty text', countVowels(''), 0);
test('case does not matter', countVowels('AEIOU'), 5);
test('both methods agree', samples.every((s) => countVowels(s) === countVowelsRegex(s)), true);

The ?? 0 — or ?? [] here — is the detail worth remembering. String.prototype.match with the g flag returns null rather than an empty array when there is no match, so text.match(...).length throws on exactly the input you would least expect to be a problem. The rhythm line prints that null so you see it.

Common mistakes

  • Forgetting about capital letters. Without toLowerCase() (or the i flag), "A" and "E" are not counted.
  • Calling .length straight on match. It crashes on any text with no vowels, because match returns null.
  • Not deciding about y. Either choice is fine, but say which one you made.

Try it yourself

  1. Add a second argument, countY, that includes y in the count when it is true.
  2. Write countConsonants(text): letters that aren't vowels. Spaces and punctuation shouldn't count.
  3. Return an object with a count for each vowel, like { a: 2, e: 0, i: 1, o: 0, u: 0 } for "javascript".

Keep practising

Newsletter

New writing, when it lands.

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