Count Vowels in String in JavaScript
Loop, check aeiou. toLowerCase first. Y is not a vowel here.
BeginnerString ProgramsExample 5 of 5
count-vowels-in-string.js
1// Method 1: Using for loop2function countVowels1(str) {3 let count = 0;4 let vowels = 'aeiouAEIOU';56 for (let i = 0; i < str.length; i++) {7 if (vowels.includes(str[i])) {8 count++;9 }10 }11 return count;12}1314console.log("Hello World:", countVowels1("Hello World"));1516// Method 2: Using for...of loop17function countVowels2(str) {18 let count = 0;19 let vowels = ['a', 'e', 'i', 'o', 'u'];2021 for (let char of str.toLowerCase()) {22 if (vowels.includes(char)) {23 count++;24 }25 }26 return count;27}2829console.log("\nUsing for...of:", countVowels2("JavaScript"));3031// Method 3: Using filter32function countVowels3(str) {33 let vowels = ['a', 'e', 'i', 'o', 'u'];34 return str.toLowerCase()35 .split('')36 .filter(char => vowels.includes(char))37 .length;38}3940console.log("Using filter:", countVowels3("Programming"));4142// Method 4: Using match with regex43function countVowels4(str) {44 let matches = str.match(/[aeiou]/gi);45 return matches ? matches.length : 0;46}4748console.log("\nUsing regex:", countVowels4("Hello World"));4950// Method 5: Using reduce51function countVowels5(str) {52 let vowels = ['a', 'e', 'i', 'o', 'u'];53 return str.toLowerCase()54 .split('')55 .reduce((count, char) => {56 return vowels.includes(char) ? count + 1 : count;57 }, 0);58}5960console.log("Using reduce:", countVowels5("Education"));6162// Method 6: Count each vowel separately63function countEachVowel(str) {64 str = str.toLowerCase();65 return {66 a: (str.match(/a/g) || []).length,67 e: (str.match(/e/g) || []).length,68 i: (str.match(/i/g) || []).length,69 o: (str.match(/o/g) || []).length,70 u: (str.match(/u/g) || []).length71 };72}7374console.log("\nEach vowel count:", countEachVowel("Hello World"));
Output
Hello World: 3
Using for...of: 3
Using filter: 3
Using regex: 3
Using reduce: 5
Each vowel count: { a: 0, e: 1, i: 0, o: 2, u: 0 }What's going on
match(/[aeiou]/gi) or a loop. i flag is ignore-case so you can skip toLowerCase.
Y is not in the set. On purpose.