Photo by Crissy Jarvis on Unsplash

The Vowel Count Test

This post is part of my Rise to the Equation series on data structures and algorithms.

The Problem

Write a function that returns the number of vowels used in a string. Vowels are the characters ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’.

— Examples
vowels(‘Hi There!’) –> 3
vowels(‘Why do you ask?’) –> 4
vowels(‘Why?’) –> 0

Source

This problem was fairly straightforward. I had used the includes() helper method in a similar problem and it worked really well. So, my first thought was to use it, along with a regular expression (regex). The includes function only works on arrays so I made sure to convert my string with split() first. Finally, I would use a for…of loop to check each letter in the array. Of course, I needed a counter because I had to return the number of matches.

function vowels(str) { 
  const array = str.split('')

  let counter = 0

  for (let letter of array) {

    if (array.includes(/[AEIOUaeiou]/g)) {
      console.log('counter: ', counter);
      counter += 1
    }
  }

  return counter
}

I got pretty far in this problem but ran into issues at the if statement. Of course, this is because I am iterating through each letter in my for loop while my if statement checks the entire array.

I decided to step back for a minute or two to collect myself. Usually the answer comes to me when I am doing something else…

Solution

There are many ways to solve this problem. One way is to do so iteratively, as I started to with my for loop above. That solution involves creating an array of all of the vowels and then checking to see if the string being passed into our function includes any of those letters. However, I don’t like the idea of hard-coding items to check against because as your application grows, that original function is going to get bloated with exceptions. Or, you will need to write a function to check each individual exception which is also unappealing.

The following solution may be succinct, but I love what it’s able to do in a few lines of code.

When I started doing research for another helper method to check my string, I found match(). This function checks str for any specified value (our vowels) and returns every item within str that matches any of our vowels.

If I set the return value to a variable called matches , then I can use it in a ternary expression. The expression checks if our matches value exists after passing in str. If so, then it reports the length of that string. Otherwise, there are no matches so it returns 0.

function vowels(str) {
  // add 'i' modifier to our regex to ignore whether upper/lowercase
  const matches = str.match(/[aeiou]/gi)

  // return the value of our ternary statement
  return matches ? matches.length : 0
}

I have worked with regex several times before this problem. However, it took me until now to start to understand how some of the more common modifiers work. Victory! I can’t wait to use it again in future projects.

Resources