I am trying to count the number of vowels in a string, but my counter does not seem to be returning more than one. Can someone please tell me what is wrong with my code? Thanks!
var vowelCount = function(str){
  var count = 0;
  for(var i = 0; i < str.length; i++){
    if(str[i] == 'a' || str[i] == 'i' || str[i] == 'o' ||str[i] == 'e' ||str[i] == 'u'){
      count+=1;
    }
  }
  return count;
}
console.log(vowelCount('aide'));
                So take a look at this one: var userData = prompt("Enter any text here"). toLowerCase(); var a = 0; var e = 0; var i = 0; var o = 0; var u = 0; var consonants = 0; var count; for (count = 0; count < userData.
JavaScript contains 3 vowels.
return count outside of for loop, or use RegExp /[^aeiou]/ig as first parameter to .replace() with "" as replacement string, get .legnth of string returned by .replace()
vowelLength = "aide".replace(/[^aeiou]/ig, "").length;
console.log(vowelLength);
vowelLength = "gggg".replace(/[^aeiou]/ig, "").length;
console.log(vowelLength);
RegExp description
Character set
[^xyz] A negated or complemented character set. That is, it matches anything that is not enclosed in the brackets.
Flags
i ignore case
g global match; find all matches rather than stopping after the first match
Using spread element, Array.prototype.reduce(), String.prototype.indexOf() or String.prototype.contains() where supported
const v = "aeiouAEIOU";
var vowelLength = [..."aide"].reduce((n, c) => v.indexOf(c) > -1 ? ++n : n, 0);
console.log(vowelLength);
var vowelLength = [..."gggg"].reduce((n, c) => v.indexOf(c) > -1 ? ++n : n, 0);
console.log(vowelLength);
Alternatively, instead of creating a new string or new array to get .length property or iterate characters of string, you can use for..of loop, RegExp.prototype.test with RegExp /[aeiou]/i to increment a variable initially set to 0 if .test() evaluates to true for the character passed.
var [re, vowelLength] = [/[aeiou]/i, 0]; 
for (let c of "aide") re.test(c) && ++vowelLength;
console.log(vowelLength); 
vowelLength = 0;
for (let c of "gggg") re.test(c) && ++vowelLength;
console.log(vowelLength); 
You need to also do this. use toLowerCase() also
 var vowelCount = function(str){
  var count = 0;
  for(var i = 0; i < str.length; i++){
    if(str[i].toLowerCase() == 'a' || str[i].toLowerCase() == 'i' || str[i].toLowerCase() == 'o' ||str[i].toLowerCase() == 'e' ||str[i].toLowerCase() == 'u'){
      count+=1;
    }
  }
 return count;
}
vowelCount('aide')
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With