JavaScript Challenge (Part 2)
We will be finding vowels in today’s code challenge!
Here are the directions:
Write a function that returns the number of vowels used in a string. Vowels are the characters 'a', 'e', 'i', 'o', and 'u'.
Here are some examples:
vowels('Hi There!') --> 3
vowels('Why do you ask?') --> 4
vowels('Why?') --> 0
For this challenge, we will look at two different solutions. One is going to be an iterative solution and the other one is going to use a regular expression.
Let’s start with the iterative solution. This solution will be fairly straightforward. We will create a counter variable at the top, and we’ll initialize it with a default value of 0. We will then iterate through all the characters inside of our string. If a given character is a vowel, we will then increment the counter and at the very end of the function, we’ll return that counter.
So we’ll start with this:
function vowels(str) {
let count = 0;
for (let char of str.toLowerCase()) {
}
return count;
}
OK, so now the next question is how are we going to check to see if we are working with a vowel?
function vowels(str) {
let count = 0;
const checker = ['a', 'e', 'i', 'o', 'u']
for (let char of str.toLowerCase()) {
if (checker.includes(char)){
count++;
}
}
return count;
}
Now, this is just one solution. Let’s go over another!
Now, this alternative solution is going to make use of a regex expression or a regular expression.
function vowels(str) {
const matches = str.match(/[aeiou]/gi);
return matches ? matches.length : 0
}
So that’s it, a very concise solution to returning the number of vowels!