
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Get Number of Vowels in a String using 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).
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
<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