Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Counting number of vowels in a string

Tags:

javascript

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'));
like image 607
Colin Sygiel Avatar asked Feb 23 '17 05:02

Colin Sygiel


People also ask

How do you calculate the number of vowels and consonants in a string JavaScript?

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.

How many vowels are there in JavaScript?

JavaScript contains 3 vowels.


2 Answers

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); 
like image 142
guest271314 Avatar answered Sep 28 '22 06:09

guest271314


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')
like image 22
Darshak Avatar answered Sep 28 '22 08:09

Darshak