Photo by Brett Jordan on Unsplash

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!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Winston Chen
Winston Chen

Written by Winston Chen

Full-Stack Web Developer, specializing in React and Ruby on Rails.

No responses yet

Write a response