Javascript Algorithms #1: Counting the Vowels in a String Of Text

Over the years, Javascript has continued to gain lots of attention as its increasingly vast capabilities continue to expand. It has grown from being just a client-side scripting language for making cool interactive web interfaces to being used extensively on the server-side, for mobile applications, desktop applications, embedded systems, IOT, and so on.

However, it’s become clear that despite the wide range of frameworks available to enhance the strengths of a Javascript developer, it eventually all boils down to understanding the basics. The ability to manipulate vanilla Javascript to do things in the most efficient way is what makes the difference. There’s really so many Javascript developers out there these days and it makes me wonder how many of us really know our stuff.

In this series, we will be implementing various algorithms using Vanilla Javascript. We will explore various solutions and examine the pros and cons of each approach. We’d also be posting links to a CodePen show-casing these implementations. It’ll benefit you most when you try to re-create these solutions on your own as well as make an attempt to improve them.

We’d recommend that you try to do it yourself first and only refer to the code to get pointed in the right direction, confirm your solutions, and study other approaches. The algorithms will range from writing basic to advance algorithms hence, some of these challenges would be indeed very challenging. Do not be discouraged. That’s the point of it all and that’s how you get to grow as a developer. So sit tight and enjoy the ride. Let’s all grow together!

The Challenge

Basically, we want to be able to receive a string of text of any length and return the number of vowels found within the text.

Algorithmic Thinking

Reading through the challenge statement above, you’d notice the statement** “receive a string of text”**. If you’re quite used to programming in general, this should bring the idea of functions to mind. We could write a function that’d have a parameter called “text”. Text would be a string of any length which would be passed to the function as an argument when it is called.

Next, within the function we have to go through the text and search for occurrences of the English vowels (a,e,i,o,u).

The function then returns the total number of matches(vowels) found. This should bring “return statements” to mind as they basically stop the execution of a function and return a value from that function.

Code Implementation

Oooooohhh yeah!!! We got the boring stuff out of the way. These algorithms won’t write themselves, would they? We’d explore two ways to implement this. First we’d follow an Iterative approach and then the use of Regular Expressions.

An Iterative Approach

In the iterative approach, we would have to loop through each letter of the string passed and then check to see if they match any of the vowels. Before running through the text we would have a counter initialized and assigned a value of zero. In a case where there’s a match, we would increment the counter. Pretty simple right?

Well here’s our implementation:

/_
An iterative approach to counting the number of vowels in a
string of text.
_/
const vowels = ["a", "e", "i", "o", "u"]


function countVowelsIterative(text) {
// Initialize counter
let counter = 0;


// Loop through text to test if each character is a vowel
for (let letter of text.toLowerCase()){
    if (vowels.includes(letter)) {
       counter++
    }
}


// Log formatted response to console
console.log(`The text contains ${counter} vowel(s)`)


// Return number of vowels
return counter
}

/_ 
    ============== Test Case ===================
_/
countVowelsIterative('I am a world-class developer using iterations');
// Logs "The text contains 16 vowel(s)" to the console
// returns 16

Well, that was pretty self explanatory right? Let’s go over some key points.

  • First, we declared a constant “vowels” which contained an array of the five English vowels.
  • Next, we make use of a for…of loop to iterate through each letter of the text. If you’re not conversant with this, a for…of loop basically creates a loop iterating over iterable objects. Iterable objects could be strings, arrays, maps, sets etc. You can learn more here.
  • Notice how we convert all letters of the text to lowercase within the loop. This is because, we don’t want to miss the cases of uppercase vowels within the passed text (trust me that wasn’t intentional).
  • Next within the loop, we use an if statement to check if the selected letter is included in the array of vowels we defined earlier. Fittingly, we call the includes() method on the array of vowels to determine whether the array includes the selected letter, returning true or false as appropriate. Learn more about how includes() works here.
  • If the condition evaluates to true, we increment the counter.
  • After looping through we log a formatted message to the console telling us the number of vowels and then return the counter which is equivalent to the number of vowels found.

Wheeewww!!! That felt good. Now let’s consider a slightly more advanced yet concise approach.

Using Regular Expressions

Regular Expressions are quite a bit of a trouble for most developers in my experience. Usually, we don’t get to understand the syntax and its application. Hence, we mostly get some snippets online when we need to make use of them. Okay then! Let’s try to change that!

Basically regular expressions help us find patterns or characters/ character combinations within strings. See why this is relevant to us? They’ll help us find the desired characters within the text passed. By extension, regular expressions can help us to do way more remarkable things such us the implementation of content filters. However, my favorite thing about Regular Expressions is the fact that the basics stay same across all languages.

Without further ado, let’s examine the solution. If you’d love to learn more about Regular Expressions in Javascript, go through the Mozilla Developer Network’s documentation here.

Here’s our implementation:


/_
Using Regular Expressions to count the number of vowels in a
string of text.

_/

function countVowelsRegex(text) {
// Search text with Regex and store all matching instances
let matchingInstances = text.match(/[aeiou]/gi);

// Check if matching instances exist then calculate length
if(matchingInstances) {
// Log formatted response to console
console.log(`The text contains ${matchingInstances.length} vowel(s)`)

// Return number of vowels
return matchingInstances.length
} else{
return 0
}
}

/_
============== Test Case ===================
_/
countVowelsRegex('I am a world-class developer uisng Regex');
// Logs "The text contains 13 vowel(s)" to the console
// returns 13

I guess you won’t need a review of this one, would you? Okay! Okay! Let’s look at the solution.

  • The first thing we did within the function was to call thematch() method on the text which returns an array of the matches found after matching the regular expression passed as an argument against the text. Learn more about how match() works here.
  • The regular expression specifies the letters to be looked for within the brackets[]. For simple patterns, Regular expressions are usually defined within a pair of slashes. Notice the characters “gi” trailing the closing slash?
  • “g” stands for a global search which does not return after the first match, restarting the subsequent searches from the end of the previous match.
  • “i” stands for case insensitive search which makes the whole expression case-insensitive (for example /xyz/i would match XyZ).
  • Next we use a conditional to check if any matching instances were found. The .match() method used above returns an array of the matched items if matches were found and “null” if they weren’t. Hence in the conditional, if “matchingInstances”evaluates to a truthy value(that is an array of matches found), we log a formatted message showing the number of vowels which is same as the length of the array. Then we return the number as well. On the other hand if it evaluates to a falsy value, we return 0 as it means no matches were found.

Evaluation & Summary

We have now successfully implemented an algorithm that counts the number of vowels in a string of text in Javascript.

Let’s evaluate both methods used. The iterative approach although not as concise as the other is an easier and somewhat more logical approach especially for beginners. However as the result below shows, the Regex method is better optimized.

Click here to run these tests by yourself.

Perhaps we could say the Regex method wins? Nevertheless, both approaches work and could be used in an interview situation.

Was this exciting for you? Let me know in the comment section below. It really was for me. We were able to successfully examine two approaches to implementing an algorithm that helps us count the number of vowels within a given piece of text. In the process, we’ve learnt about some Javascript methods and regular expressions. These tools are very important items in a Modern Javascript Developer’s toolbox.

Feel free to implement this in other ways and explore the pros and cons of using each method. Also share them with others in the comment section (possibly a link to your pen). We look forward to seeing them. Ask questions as well. I’m sure we’d find the answers somehow.

Please share this article with other’s too if you found it helpful.