Colin Sygiel
Colin Sygiel

Reputation: 947

Javascript: Counting number of vowels in a string

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'));

Upvotes: 6

Views: 4970

Answers (2)

guest271314
guest271314

Reputation: 1

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

Upvotes: 7

Darshak
Darshak

Reputation: 867

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

Upvotes: 1

Related Questions