0

My little function doesn't seem to update the totalVowels variable. My train of thought at the moment is: the argument is converted into an array, the array is iterated through, and if the index matches against my vowel regex, my totalVowels var will add 1 per each match.

I feel like the solution is right under my nose, but I've been changing lots of little things around to get this to work and I'm currently out of ideas.

    function VowelCount(str) {
     let strArr = str.split('');
     let totalVowels  = 0;
     let vowel = /a|e|i|o|u/gi
     for (let i = 0; i < strArr.length; i++) {
        if (strArr[i] === vowel) { totalVowels++ }
     }
     return totalVowels;
    }
    
    console.log(VowelCount('vowel'));
Liam
  • 27,717
  • 28
  • 128
  • 190
kevin
  • 2,707
  • 4
  • 26
  • 58

1 Answers1

4

Use .match() instead of strArr[i] === vowel for your if condition check because you're using a regex:

function VowelCount(str) {
  let strArr = str.split('');
  let totalVowels = 0;
  let vowel = /a|e|i|o|u/gi
  for (let i = 0; i < strArr.length; i++) {
    if (strArr[i].match(vowel)) {
      totalVowels++
    }
  }
  return totalVowels;
}

console.log(VowelCount('hello there'));
slider
  • 12,810
  • 1
  • 26
  • 42