Count the vowels in a string

“Vowel counter”, a White belt challenge from the CurlyScript Dojo. It uses what Grade 5: Loops: Doing Things Over and Over teaches, and 4 tests check your answer.

The challenge

Write countVowels(text) that returns how many vowels (a, e, i, o, u) are in the text. Count capital letters too.

Example
countVowels("Welcome")  // 3

Try it

Write your answer below, then press Check my answer. Your code runs right here in your browser, and the tests tell you what works.

What the tests check

  • countVowels("Welcome") gives 3
  • countVowels("JavaScript") gives 3
  • countVowels("rhythm") gives 0
  • countVowels("") gives 0

Hints

Stuck? Open one hint at a time. Try again after each one.

Hint 1

Loop over the characters with for…of.

Hint 2

"aeiou".includes(char.toLowerCase()) tells you if a character is a vowel.

A solution

There’s always more than one right way. Read it, make sure you understand it, then try writing it yourself without looking.

Show one possible solution
Solution
function countVowels(text) {
  let count = 0;
  for (const char of text) {
    if ("aeiou".includes(char.toLowerCase())) count++;
  }
  return count;
}

Learn what you need

This exercise uses what Grade 5: Loops: Doing Things Over and Over teaches. Read those notes first if any of it is new.

Practice makes it stick

CurlyScript is a free game that teaches JavaScript from zero: short lessons, an explanation after every answer, and Dojo challenges like this one.

Start learning