Tutorialspoint

1 Answer
vineeth.mariserla

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). 

Debrief

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.

Example

Live Demo

<html>
<body>
<script>
   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"));
</script>
</body>
</html>

Output

12
Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.