Javascript Algorithms #1: Counting the Vowels in a String Of Text
Tags: javascript, algorithms, performance
Published: 2018-07-26 04:58:53

---
title: Javascript Algorithms #1: Counting the Vowels in a String Of Text
published: true
description: Basically, we want to be able to receive a string of text of any length and return the number of vowels found within the…
tags: javascript, algorithms, performance
---

---
![](https://thepracticaldev.s3.amazonaws.com/i/5ne3lavoy7gyxyvm984t.png)
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
![](https://cdn.scotch.io/57596/SBgHo3lCTfubIHmEo7Or_0_w9ZqNj9KDG3zkYus.jpeg)


"Men! This isn't as easy as i thought" by Tim Gouw on UnsplashReading 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:
```javascript
/*
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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol). Iterable objects could be strings, arrays, maps, sets etc. You can learn more [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of).
* 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes).
* 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions).

Here's our implementation:
```javascript
/*
    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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match).
* 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.

![](https://cdn.scotch.io/57596/Dd99tsKRaKtALNXDvjQn_0_OikT1OG_q9MPkOQ3.jpeg)



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.
![](https://cdn.scotch.io/57596/IpJeMXs1TIaK9KGUZOqH_1_RWbGd1aYfPpjTlM6SdRckQ.png)

Click [here](https://jsperf.com/vowel-counter) 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 everyone 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. You received freely, give freely. I also won't mind a round of applause you know (***winks***).

Connect with me on twitter will you? [@worldclassdev](http://twitter.com/worldclassdev)

**[SUBSCRIBE FOR UPDATES HERE](https://medium.com/dev-process) & STAY TUNED FOR THE NEXT ARTICLE ON THE SERIES.**