count vowels in a string javascript

Count Vowels in a String using Javascript

Counting the number of vowels in a given string is a common task in programming. In Javascript, we can do this by looping through each character in the string and checking if it is a vowel or not.

Method 1:

One way to count vowels in a string is to use a regular expression to match all the vowels and then count the number of matches.


function countVowels(str) {
  return (str.match(/[aeiou]/gi) || []).length;
}
  • str.match(/[aeiou]/gi) matches all the vowels in the string.
  • (str.match(/[aeiou]/gi) || []) returns an array of matches or an empty array if there are none.
  • (str.match(/[aeiou]/gi) || []).length returns the length of the array, which is the number of vowels in the string.

Method 2:

Another way to count vowels in a string is to loop through each character in the string and check if it is a vowel.


function countVowels(str) {
  var count = 0;
  for (var i = 0; i < str.length; i++) {
    if (/[aeiou]/.test(str[i])) {
      count++;
    }
  }
  return count;
}
  • var count = 0; initializes a variable to keep track of the number of vowels.
  • for (var i = 0; i < str.length; i++) loops through each character in the string.
  • if (/[aeiou]/.test(str[i])) checks if the current character is a vowel.
  • count++; increments the count if the current character is a vowel.
  • return count; returns the total number of vowels in the string.

Usage:

To use the function, simply call it with a string as an argument:


var str = "Hello World";
var vowels = countVowels(str);
console.log(vowels); // output: 3

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe