Unlock the Power of JavaScript: Counting Vowels with Ease

When it comes to mastering JavaScript, understanding how to work with strings is essential. One common task is counting the number of vowels in a given string. But how do you do it efficiently? Let’s dive into two different approaches to solve this problem.

The Regex Way: A Concise Solution

Regular expressions (regex) are a powerful tool in JavaScript, and they can be used to count vowels with ease. The regex pattern /[aeiou]/gi is the key to success. This pattern matches all vowels (both lowercase and uppercase) in a string. By combining it with the match() method, you can extract an array of all vowels present in the string. Finally, the length property gives you the total count of vowels.


function countVowels(str) {
  const vowels = str.match(/[aeiou]/gi);
  return vowels.length;
}

console.log(countVowels("Hello World")); // Output: 3

The Loop Approach: A Step-by-Step Solution

Sometimes, you may prefer a more straightforward approach. That’s where a simple for...of loop comes in. By iterating over each character in the string, you can check if it’s a vowel using the includes() method. If it is, increment a counter variable.


function countVowels(str) {
  const vowels = ['a', 'e', 'i', 'o', 'u'];
  let count = 0;

  for (const char of str.toLowerCase()) {
    if (vowels.includes(char)) {
      count++;
    }
  }

  return count;
}

console.log(countVowels("Hello World")); // Output: 3

By using these two approaches, you can efficiently count the number of vowels in a string. Whether you prefer the concise regex solution or the step-by-step loop approach, you’ll be able to tackle this common task with confidence.

Leave a Reply