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 loop
2function countVowels1(str) {
3 let count = 0;
4 let vowels = 'aeiouAEIOU';
5
6 for (let i = 0; i < str.length; i++) {
7 if (vowels.includes(str[i])) {
8 count++;
9 }
10 }
11 return count;
12}
13
14console.log("Hello World:", countVowels1("Hello World"));
15
16// Method 2: Using for...of loop
17function countVowels2(str) {
18 let count = 0;
19 let vowels = ['a', 'e', 'i', 'o', 'u'];
20
21 for (let char of str.toLowerCase()) {
22 if (vowels.includes(char)) {
23 count++;
24 }
25 }
26 return count;
27}
28
29console.log("\nUsing for...of:", countVowels2("JavaScript"));
30
31// Method 3: Using filter
32function 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}
39
40console.log("Using filter:", countVowels3("Programming"));
41
42// Method 4: Using match with regex
43function countVowels4(str) {
44 let matches = str.match(/[aeiou]/gi);
45 return matches ? matches.length : 0;
46}
47
48console.log("\nUsing regex:", countVowels4("Hello World"));
49
50// Method 5: Using reduce
51function 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}
59
60console.log("Using reduce:", countVowels5("Education"));
61
62// Method 6: Count each vowel separately
63function 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) || []).length
71 };
72}
73
74console.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.