Strings · beginner
JavaScript Program to Count the Vowels in a String
Count the vowels in a string in JavaScript with a loop and includes(), count each vowel in an object, and do it in one line with a regex and match().
- for...of over a string
- includes()
- objects as counters
- match() with a regex
Counting vowels is a small exercise in looping over characters, testing membership and keeping counts. The program counts all vowels and, at the same time, each vowel separately in an object.
The same pattern counts digits, spaces or capital letters, so it is worth understanding before using the one-line regex version.
The program
const text = "Programming in JavaScript is fun";
const counts = { a: 0, e: 0, i: 0, o: 0, u: 0 };
let total = 0;
for (const ch of text.toLowerCase()) {
if ("aeiou".includes(ch)) {
total++;
counts[ch]++;
}
}
console.log("Vowels:", total);
console.log(JSON.stringify(counts));Vowels: 9
{"a":3,"e":0,"i":4,"o":1,"u":1}How it works
- counts starts with a zero for each vowel; total counts all of them.
- toLowerCase() makes capital vowels count too.
- "aeiou".includes(ch) is true when the character is one of the five vowels.
- counts[ch]++ uses the character as the property name, so each vowel gets its own count.
- JSON.stringify prints the object on one line.
Watch it run line by line
Watch the counts object in the global frame: one count changes each time the highlighted line reaches counts[ch]++, and total follows.
“Visualize step by step” opens the program in the JavaScript Compiler and records every step in your browser. Use the arrow keys to move forwards and backwards; changed variables are highlighted.
Another way: One line with match()
match() with the g and i flags returns an array of every vowel, or null when there is none, so ?? [] handles that case.
const text = "Programming in JavaScript is fun";
console.log((text.match(/[aeiou]/gi) ?? []).length);
console.log(("xyz".match(/[aeiou]/gi) ?? []).length);9
0Common mistakes
- Forgetting toLowerCase() or the i flag, so capital vowels are missed.
- Calling .length on the result of match() directly: it is null when nothing matches, which throws TypeError.
- Using text.split("aeiou"), which splits on the five-letter sequence "aeiou", not on single vowels.
- Accented vowels such as "é" are not in "aeiou". Remove the accents first with text.normalize("NFD").replace(/[\u0300-\u036f]/g, "") if they should count.
Try it yourself
- Count consonants as well (letters that are not vowels).
- Remove all vowels from the sentence with replace().
Open the program in the JavaScript Compiler, change it and press Run: there is nothing to install, and your code never leaves your browser.
Related examples
Browse all 25 JavaScript examples, or write your own program in the online JavaScript Compiler.