The purpose of this exercise is to count the number of vowels in a string. This is actually pretty easy using a regex expression. I use the match() method to pick out the vowels [aeiou]. The “g” in “/gi” tells the expression to match all occurrences, not just the first one. The “i” tells it to find either capital or lower case letters.
//OPTION 1 - REGEX EXPRESSION
function vowels(str) {
const vowelMatch = str.match(/[aeiou]/gi);
const length = vowelMatch === null ? 0 : vowelMatch.length;
console.log ('str ', str, 'vowel ', vowelMatch, 'length ', length);
return length;
}
I used a nested for loop to do it a longer way.
// OPTION 2 - USING FOR LOOPS
function vowels (str) {
const vowelList = ["a","e","i","o","u"];
const strArray = str.toLowerCase().split("");
let vowelCount = 0;
for (let i = 0; i<strArray.length; i++) {
for (let j=0; j<vowelList.length; j++)
if (strArray[i] === vowelList[j]) {
vowelCount += 1;
}
}
return vowelCount;
}
Finally, I used a for…of loop to complete it. Not as easy as a regex expression, but more efficient than a nested loop.
// OPTION 3 - FOR...OF LOOP
function vowels(str) {
const vowelList = ["a","e","i","o","u"];
let vowelCount = 0;
for (let char of str.toLowerCase()) {
if(vowelList.includes(char)) {
vowelCount++;
}
}
return vowelCount;
}