How To Count Vowels in a String of Text Using JavaScript Algorithms

PostedDecember 12, 2019 663 views JavaScript

While this tutorial has content that we believe is of great benefit to our community, we have not yet tested or edited it to ensure you have an error-free learning experience. It's on our list, and we're working on it! You can help us out by using the "report an issue" button at the bottom of the tutorial.

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. Although there are a wide range of frameworks available to enhance the strengths of a JavaScript developer, learning to work with vanilla JavaScript to do things in the most efficient way is a fundamental skill.

In this article you’ll implement two different algorithm approaches using vanilla JavaScript. It’s recommended that you try to do it yourself first and only refer to the code to move in the right direction, confirm your solutions, and study other approaches.

Your challenge is 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, you’ll 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. You can stop the execution of a function and return a value from that function with return statements.

Code Implementation

We’ll explore two ways to implement this. First an iterative approach and then the use of regular expressions.

An Iterative Approach

In the iterative approach, we’ll 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 increment the counter.

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
  • 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 creates a loop iterating over iterable objects. Iterable objects could be strings, arrays, maps, sets, and so on.
  • 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.
  • 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.

Now let’s consider another approach.

Regular Expressions

Regular expressions help us find patterns or characters/character combinations within strings. This is relevant to us because regular expressions will help us find the desired characters within the text passed. By extension, regular expressions can help us to do more remarkable things such as the implementation of content filters. Regular expressions also stay the same across programming languages. Let’s examine the solution.

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 using Regex');
    // Logs "The text contains 13 vowel(s)" to the console
    // returns 13
  • 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.
  • 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 false 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 can be a more logical approach, especially for beginners. However as the result shows, the regex method is better optimized.
results in vowel counter showing test case with regex having better optimization

You can use this test case vowel counter to run the tests yourself.

0 Comments

Creative Commons License