Count Number of Vowels in Given String

JavaScript

Count the number of vowels in a given string:

Create a function in JavaScript to count the number of vowels in a given string by iterating through the string and checking if each character is a vowel. Here's how you can implement it:

js Copy Code
function countVowels(str) {
  const vowels = ['a', 'e', 'i', 'o', 'u'];
  let count = 0;
  
  // Convert the string to lowercase 
  str = str.toLowerCase();
  
  // Iterate through the string
  for (let char of str) {
    // Check if the character is a vowel
    if (vowels.includes(char)) {
      count++;
    }
  }
  
  return count;
}

// Example usage:
const text = "Hello, how are you?";
const vowelCount = countVowels(text);
console.log("Number of vowels:", vowelCount);
Output:
Number of vowels: 7

Explanation:

1. We define an array 'vowels' containing all lowercase vowels.

2. We initialize a variable 'count' to keep track of the number of vowels found.

3. Convert the input string to lowercase using 'toLowerCase()' to handle both uppercase and lowercase vowels uniformly.

4. We iterate through the string character by character.

5. For each character, we check if it's a vowel by using the 'includes()' method to see if it's in the 'vowels' array.

6. If a character is a vowel, we increment the 'count' variable.

7. Finally, we return the 'count' variable, which holds the total number of vowels in the string.

What's Next?

We've now entered the finance section on this platform, where you can enhance your financial literacy.