Find The Vowels used in a String with JavaScript
Tadea Simunovic
Posted on May 27, 2020
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
Posted on May 27, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.