Counting vowels and consonants in a string is a classic string-processing exercise: loop through each character, check whether it’s a letter, and classify it as a vowel (a, e, i, o, u) or a consonant.
JavaScript Program to Count Vowels and Consonants in a String
function countVowelsAndConsonants(str) {
const vowels = "aeiouAEIOU";
let vowelCount = 0;
let consonantCount = 0;
for (const char of str) {
if (!/[a-zA-Z]/.test(char)) continue; // skip spaces, digits, punctuation
if (vowels.includes(char)) {
vowelCount++;
} else {
consonantCount++;
}
}
return { vowelCount, consonantCount };
}
const result = countVowelsAndConsonants("Simple2Code JavaScript Tutorials");
console.log(`Vowels: ${result.vowelCount}, Consonants: ${result.consonantCount}`);
Output:
Vowels: 11, Consonants: 18
The for...of loop here walks the string one character at a time, the same idea as reversing a string character by character. The regular expression /[a-zA-Z]/ filters out anything that isn’t a letter, so digits and spaces in the input don’t get miscounted as consonants — a common bug in naive versions of this program. You can extend this same pattern to also count digits and special characters by adding similar checks inside the loop.
