11

I'm using basic JavaScript to count the number of vowels in a string. The below code works but I would like to have it cleaned up a bit. Would using .includes() help at all considering it is a string? I would like to use something like string.includes("a", "e", "i", "o", "u") if at all possible to clean up the conditional statement. Also, is it needed to convert the input into a string?

function getVowels(str) {
  var vowelsCount = 0;

  //turn the input into a string
  var string = str.toString();

  //loop through the string
  for (var i = 0; i <= string.length - 1; i++) {

  //if a vowel, add to vowel count
    if (string.charAt(i) == "a" || string.charAt(i) == "e" || string.charAt(i) == "i" || string.charAt(i) == "o" || string.charAt(i) == "u") {
      vowelsCount += 1;
    }
  }
  return vowelsCount;
}
1
  • in a for loop after string.length the "-1" is not needed if you don't use <"=". would look better if "=" are removed as well as "-1".
    – Sirmais
    Sep 9, 2021 at 7:14

25 Answers 25

38

You can actually do this with a small regex:

function getVowels(str) {
  var m = str.match(/[aeiou]/gi);
  return m === null ? 0 : m.length;
}

This just matches against the regex (g makes it search the whole string, i makes it case-insensitive) and returns the number of matches. We check for null incase there are no matches (ie no vowels), and return 0 in that case.

0
12

Convert the string to an array using the Array.from() method, then use the Array.prototype.filter() method to filter the array to contain only vowels, and then the length property will contain the number of vowels.

const countVowels = str => Array.from(str)
  .filter(letter => 'aeiou'.includes(letter)).length;

console.log(countVowels('abcdefghijklmnopqrstuvwxyz')); // 5
console.log(countVowels('test')); // 1
console.log(countVowels('ddd')); // 0

1
  • Hello, but the filter method will remove duplicate, i mean if the string have two a's for example the filter method will only return the first one ? no ? Jul 8, 2021 at 20:45
7
function countVowels(subject) {
    return subject.match(/[aeiou]/gi).length;
}

You don't need to convert anything, Javascript's error handling is enough to hint you on such a simple function if it will be needed.

2
  • 2
    It doesn't work when subject doesn't contain any vowels. Nov 22, 2016 at 13:02
  • 3
    return (subject.match(/[aeiou]/gi) || []).length; change to this just in case
    – maximast
    Jun 1, 2017 at 19:35
5

Short and ES6, you can use the function count(str);

const count = str => (str.match(/[aeiou]/gi) || []).length;
4

This could also be solved using .replace() method by replacing anything that isn't a vowel with an empty string (basically it will delete those characters) and returning the new string length:

function vowelCount(str) {
  return str.replace(/[^aeiou]/gi, "").length;
};

or if you prefer ES6

const vowelCount = (str) => ( str.replace(/[^aeiou]/gi,"").length )
4

You can convert the given string into an array using the spread operator, and then you can filter() the characters to only those which are vowels (case-insensitive).

Afterwards, you can check the length of the array to obtain the total number of vowels in the string:

const vowel_count = string => [...string].filter(c => 'aeiou'.includes(c.toLowerCase())).length;

console.log(vowel_count('aaaa'));            // 4
console.log(vowel_count('AAAA'));            // 4
console.log(vowel_count('foo BAR baz QUX')); // 5
console.log(vowel_count('Hello, world!'));   // 3

4

Use this function to get the count of vowels within a string. Works pretty well.

function getVowelsCount(str)
{
  //splits the vowels string into an array => ['a','e','i','o','u','A'...]
  let arr_vowel_list = 'aeiouAEIOU'.split(''); 


  let count = 0;
  /*for each of the elements of the splitted string(i.e. str), the vowels list would check 
    for any occurence and increments the count, if present*/
  str.split('').forEach(function(e){
  if(arr_vowel_list.indexOf(e) !== -1){
   count++;} });


   //and now log this count
   console.log(count);}


//Function Call
getVowelsCount("World Of Programming");

Output for the given string would be 5. Try this out.

//Code -

  function getVowelsCount(str)
   {
     let arr_vowel_list = 'aeiouAEIOU'.split(''); 
     let count = 0;
     str.split('').forEach(function(e){
     if(arr_vowel_list.indexOf(e) !== -1){
     count++;} });
     console.log(count);
   }
1
  • 1
    Hi, you should explain your answer. So others who looks for the answer will understand. Thanks
    – ZeroOne
    Oct 25, 2019 at 1:47
4

You can use the simple includes function, which returns true if the given array contains the given character, and false if not.

Note: The includes() method is case sensitive. So before comparing a character convert it to lowercase to avoid missing all the possible cases.

for (var i = 0; i <= string.length - 1; i++) {
  if ('aeiou'.includes(string[i].toLowerCase())) {
    vowelsCount += 1;
  }
}
3

This is the shortest solution

 function getCount(str) {
 return (str.match(/[aeiou]/ig)||[]).length;
 }
3

Use match but be careful as it can return a null if no match is found. This solves it:

const countVowels = (subject => (subject.match(/[aeiou]/gi) || []).length);
3
function vowels(str) {
   let count=0;
   const checker=['a','e','i','o','u'];
   for (let char of str.toLowerCase){
      if (checker.includes(char)) {
        count++;
      }
   return count;
}


function vowels(str) {
   const match = str.match(/[aeiou]/gi);
   return match ? match.length : 0 ;
}
2

count = function(a) {
  //var a=document.getElementById("t");
  console.log(a); //to see input string on console
  n = a.length;
  console.log(n); //calculated length of string
  var c = 0;
  for (i = 0; i < n; i++) {
    if ((a[i] == "a") || (a[i] == "e") || (a[i] == "i") || (a[i] == "o") || (a[i] == "u")) {
      console.log(a[i]); //just to verify
      c += 1;
    }
  }

  document.getElementById("p").innerText = c;
}
<p>count of vowels </p>
<p id="p"></p>
<input id="t" />
<input type="button" value="count" onclick="count(t.value)" />

2

const containVowels = str => {
  const helper = ['a', 'e', 'i', 'o', 'u'];

  const hash = {};

  for (let c of str) {
    if (helper.indexOf(c) !== -1) {
      if (hash[c]) {
        hash[c]++;
      } else {
        hash[c] = 1;
      }
    }
  }

  let count = 0;
  for (let k in hash) {
    count += hash[k];
  }

  return count;
};

console.log(containVowels('aaaa'));

2

As the introduction of forEach in ES5 this could be achieved in a functional approach, in a more compact way, and also have the count for each vowel and store that count in an Object.

function vowelCount(str){
  let splitString=str.split('');
  let obj={};
  let vowels="aeiou";
  splitString.forEach((letter)=>{
    if(vowels.indexOf(letter.toLowerCase())!==-1){
      if(letter in obj){
        obj[letter]++;
      }else{
        obj[letter]=1;
      }
    }   

 });
 return obj;    
}
2

My solution:

const str = "In West Philadephia, born and raised.";
const words = str.split("");

function getVowelCount() {
    return words.filter(word => word.match(/[aeiou]/gi)).length;
}

console.log(getVowelCount());

Output: 12

2

You can easily solve this using simple regex. match() method matches string agains a regex variable. return an array if the is a matches and return null if no match is found.

function getVowels(str) {
  let vowelsCount = 0;

  const regex = /[aiueo]/gi;
  vowelsCount = str.match(regex);

  return vowelsCount ? vowelsCount.length : 0;
}

console.log(getVowels('Hello World')) => return 3
console.log(getVoewls('bbbcccddd') => return 0

1

Just use this function [for ES5] :

function countVowels(str){
    return (str.match(/[aeiou]/gi) == null) ? 0 : str.match(/[aeiou]/gi).length;        
}

Will work like a charm

1
    (A)   
     const countVowels = data => [...data.toLowerCase()].filter(char => 'aeiou'.includes(char)).length;

    (B)    
      const countVowels = data => data.toLowerCase().split('').filter(char => 'aeiou'.includes(char)).length;

    countVowels("Stackoverflow") // 4 
1

The following works and is short:

 function countVowels(str) {
 return ( str = str.match(/[aeiou]/gi)) ? str.length : 0;
}


console.log(countVowels("abracadabra")); // 5
console.log(countVowels(""));            // 0

1

One more method (using reduce):

   function getVowels(str) {
     return Array.from(str).reduce((count, letter) => count + 'aeiou'.includes(letter), 0);
   }
1

Here is the my solution for the problem:

function getVowelsCount(s) {
      let vowels = ["a", "e", "i", "o", "u"];
      let count=0;

    for(let v of s) {
        if(vowels.includes(v)){
            console.log(v);
            count=count+1;
        }
           
    }
     console.log(count);

}
1

After research and without using regex, this is what I found the simplest to understand for new devs like me.

function vowelCount (string) {
  let vowel = "aeiouy"; // can also be array
  let result = 0;

  for (let i = 0; i < string.length; i++) {
    
    if (vowel.includes(string[i].toLowerCase())) {
      result++;
    }
  }

    
  return result;
}



console.log(vowelCount("cAkeYE"));

1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jan 15, 2022 at 7:30
0
function vowelCount(str){
str=str.toLowerCase()
let count=[]
for(let i=0;i<str.length;i++){
if(str.charAt(i)=='u'||str.charAt(i)=='o'||str.charAt(i)=='i'||str.charAt(i)=='e'||str.charAt(i)=='a'){
  count.push(str.charAt(i))//to store all the vowels in an array
   }
}
let eachcount={}
count.forEach((x)=>eachcount[x]?eachcount[x]++:eachcount[x]=1) //to count each vowel from the count array
return eachcount
}
console.log(vowelCount("hello how Are You"))
0
function vowelsCount(sentence) {
let vowels = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"];
let count = 0;
let letters = Array.from(sentence);
letters.forEach(function (value) {
 if (vowels.includes(value)) {
  count++
   }
})
 return count;
}
console.log(vowelsCount("StackOverFlow"));
-1

Another solution using Set to lookup characters in constant time and reduce() to do the actual counting. The implementation also uses the spread syntax for string as strings are Iterable.

/**
 * Count vowels in a string. Ignores case.
 * @param {string} str String to count the vowels in
 * @returns numbers of vowels
 */
function countVowels(str) {
    let vowels = new Set("aeiou")
    return [...str.toLowerCase()].reduce((count, character) => count + vowels.has(character) || 0, 0)
};

console.log(countVowels("apple"))
console.log(countVowels("pears are yummy"))
.as-console-wrapper { max-height: 100% !important; top: 0; }

Not the answer you're looking for? Browse other questions tagged or ask your own question.