How to get a number of vowels in a string in JavaScript?

Calculating number of vowels in a string

Vowels in English language are a,e,i,o and u. Make sure that, in any string these vowels can be both cases ( either small or capital). 


The following example, using a user defined function called 'noOfVowels()', reads an input string and compares that string with another string which contains only vowels( 'aAeEiIoOuU'). It takes the help of indexOf() method to proceed the task. 

The indexOf() method displays index of a character whenever the character is common to both the strings, in unmatched case it displays '-1' as the output. Here it compares each and every character of the input string to the vowel string and whenever vowels got matched, it internally increments a user defined variable called "vowelsCount", which is initially 0. Eventually, the value in the "vowelsCount" is displayed as the output.


Live Demo

   function noOfVowels(string) {
      var listOfVowels = 'aAeEiIoOuU';
      var vowelsCount = 0;
      for(var i = 0; i < string.length ; i++) {
         if (listOfVowels.indexOf(string[i]) !== -1) {
            vowelsCount += 1;
   return vowelsCount;
   document.write(noOfVowels("Tutorix is one of the best e-platforms"));



Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started