Javascript: counting the 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 return 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; } console.log(count); return count; } } vowelCount('aide') 
+5
source share
2 answers

return count outside the for loop or use RegExp /[^aeiou]/ig as the first parameter .replace() with "" as a replacement string, get .legnth 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] Negative or padding character set. That is, it matches any that is not enclosed in parentheses.

Flags

i ignore case

g global compliance; find all matches, not stop after the first match


Using the extended 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 a new array to get the .length property or repeating the characters of the string, you can use the for..of , RegExp.prototype.test with RegExp /[aeiou]/i to increase the initial variable by 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); 
+6
source

You also need to 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') 
+1
source

Source: https://habr.com/ru/post/1264604/


All Articles