DEV Community

Philip Obosi
Philip Obosi

Posted on

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

"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:

/*
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

Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 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

SUBSCRIBE FOR UPDATES HERE & STAY TUNED FOR THE NEXT ARTICLE ON THE SERIES.

Top comments (16)

Collapse
 
boianivanov profile image
Boian Ivanov • Edited

A really good article for explaining algorithms through JavaScript for beginners. Good job and keep it up.

I thought though to try and add one more way of doing it, and that's recursively.
So here is my method for recursively finding the amount of vowels (feel free to use it).

const vowels = ["a", "e", "i", "o", "u"]

var count = 0;

function countVowelsRecursive(text) {
    if(vowels.includes(text[0].toLowerCase())) {
        count++;
    }
    if(text.length == 1){
        console.log(`The text contains ${count} vowel(s)`);
        return count;
    } else {
        countVowelsRecursive(text.substr(1));
    }
}

countVowelsRecursive('I am a world-class developer using iterations');
Enter fullscreen mode Exit fullscreen mode

The two important places are :

  • text[0] - gives us the first character of a string, because a string could be compared to an array of chars, and
  • text.substr(1) - removes the first character of the string, while it gives it to the method.

After those two, if we're left with only one character the method gives us the result and returns the counter.

Collapse
 
dimkl profile image
Dimitris Klouvas

It may be a correct algorithm but the implementation is not a very good one. The countVowelsRecursive should be a pure function and not depend to scoped count variable. What happens when we run the countVowelsRecursive twice in the same code snippet? Is the result of the 1st call the same as the 2nd?

Collapse
 
boianivanov profile image
Boian Ivanov

No worries, you can make it a function in a function with the parent one having the count = 0 and then the child one doing the iteration. Though you got the point that the idea behind it was to showcase different algorithms, right ?

Thread Thread
 
dimkl profile image
Dimitris Klouvas

Yeah, i mentioned that the algorithm is correct at the beginning. But i felt the urge to comment about the implementation because i think it matters. Nevermind, the topic is about the algorithm so let's move on.

Collapse
 
worldclassdev profile image
Philip Obosi

Awesome work Boain. Did you test the performance implications?

Collapse
 
boianivanov profile image
Boian Ivanov

I haven't tried, because I made it in like 10 minutes. But I presume it's could be close to yours. If you willing to test, do post the results here for future reference. I would be really interested to know.

Collapse
 
dallgoot profile image
dallgoot

i'm sorry : i've tried to run an alternate version of the first function and ended spamming tests :/
I'm also performance obsessed ;)

Collapse
 
worldclassdev profile image
Philip Obosi

Awesome Dallgoot. What's the issue with the tests?

Collapse
 
dallgoot profile image
dallgoot

No issues with the tests but many with the guy (me) who tried to make changes in them ;)
i wanted to try a version with a switch replacing the array check to see perf differences but failed miserably for some reason...

Collapse
 
dallgoot profile image
dallgoot

finally: I got some tests working (Revision 7, you can delete others)
So I'm seeing what I expected: switch cases are faster than array searching.
Not from much though, but still with so few values.

Thread Thread
 
worldclassdev profile image
Philip Obosi

Nice one man. Seen it.

Collapse
 
munamohamed94 profile image
Muna Mohamed

Great post Justine! Very detailed and well explained!

Collapse
 
worldclassdev profile image
Philip Obosi

Thanks alot Muna. That's the whole point of Series (Dev-process).

Collapse
 
zac11 profile image
Rahul Yadav

Looking forward to more such tutorials.

Collapse
 
worldclassdev profile image
Philip Obosi

Definitely Rahul... I'll keep sharing

Collapse
 
lakshmias profile image
Lakshminarayanan

is it ok to use javascript split ?
jsfiddle.net/qxd945eo/1/