Count the number of vowels

Question: Write a program to Count the Number of Vowels in a String.

The five letters a, e, i, o, u are called vowels. All other alphabets except these 5 vowels are called consonants.

Method 1: Count the Number of Vowels Using Regex
  • The regular expression (RegEx) pattern is used with the match() method to find the number of vowels in a string.
  • The pattern /[aeiou]/gi checks for all the vowels (case-insensitive) in a string.

For the input “javascript” str.match(/[aeiou]/gi); gives [“a”, “a”, “i”] * The length property gives the number of vowels present.

//Using inbuilt function

function countVowel(str) { 

    // find the count of vowels
    const count = str.match(/[aeiou]/gi).length;

    // return number of vowels
    return count;
}

const result = countVowel("javascript");

console.log(result);
//Prints: 3
Method 2:
//Without using inbuilt function

function countVowels(str) {
  let count=0;
  for(let i=0; i<str.length; i++) {
    if(str[i]==="a" || str[i]==="e" || str[i]==="i" || str[i]==="o" || str[i]==="u") {
        count+=1;
     }
   }
   return count;
}

console.log(countVowels("hello"));
//Prints: 2