It’s counting vowels in a string and here is how I solved it:
function countVowels(str) {
let result = 0;
let vowels = "aeiou"
for (let i = 0; i < str.length; i++) {
for (let j = 0; j < vowels.length; j++) {
if (str[i] === vowels[j]) {
result++;
}
}
}
return result;
};
What is the way to do it without using a second for loop? I tried indexOf but couldn’t figure it out. Things like if (str.indexOf(vowels) === -1)
Instead of iterating through vowels each time, you could just hard code your comparisons manually.
Alternatively, you could try using Regular Expressions, which would eliminate the need for the for loops entirely.
function countVowels(str) {
let result = 0;
for (let i = 0; i < str.length; i++) {
let character = str[i];
switch(character){
case a:
case e:
case i:
case o:
case u:
result++;
break;
}
}
return result;
};
I like that second one. I don’t think that would have been my first thought, but it really makes sense. Still like me my regex though. And for me, I find I really need to practice with regular expressions, they tend to get muddy in my brain.