Count the vowels in a string with JavaScript. Short and simple!
Challenge
---Directions
Write a function that returns the number of vowels used in a string. To confirm, vowels are the characters 'a', 'e', 'i', 'o' and 'u'.
---Example
vowels('Hello') ---> 2
vowels('Javascript') ---> 3
vowels('crypt') ---> 0
We will start with creating a counter variable starting with 0, and then we will iterate through our string and make sure we will lowerCase our vowels.
function vowels(str) {
let counter = 0;
for (let char of str.toLowerCase()){
}
}
We could of do a bunch of IF statements, but our code would look messy. Instead, we will use the helper method includes() that determines whether an array includes a certain value among its entries, returning true or false as appropriate. Read more about it here.
Let's create an array that will hold all of our vowels.
const check = ['a','e','i','o','u']
Now we have to use some logic in our loop. If the char that we are looking for is included in an array we will increment the counter. We'll iterate through all of our characters and then return them.
function vowels(str) {
let counter = 0;
const check = ['a','e','i','o','u']
for (let char of str.toLowerCase()){
if (check.includes(char)) {
counter++
}
}
return counter
}
Output in console.
// vowels("Today is a rainy day!") --> 7
// vowels("Shy gypsy slyly spryly tryst by my crypt") --> 0
Top comments (4)
Nice post! Also very important for beginners since you structured and explained very well. Good Job. If i had to do it, i would go with regex:
It just removes everything that is not a vowel and returns the new string size. The
i
tells it to be case insensitive.Great advice! Thank you
I know this is massively illegible compared to your beautifully constructed routine (which might well be how I'd write it because I'm all for legibility) but the short version might be coded as:
Yeah, this is no bueno. LOL.
For those trying to understand...
str
is the target decomposed into a character-arraya
represents the accumulator in the callback that is initialized to be a counter of0
which is at the end as the second argument toArray.prototype.reduce
.c
represents the character (letter)a
(accumulator/counter) +1
if the character,c
, is found, and0
otherwise using a ternary operator expression.I love
Array.prototype.reduce
, too, but this is not expressive LOL.Using good variable names here is important IMO: