Tutorial

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

Updated on April 7, 2021
Default avatar

By Philip Obosi

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

Introduction

The phrase vanilla JavaScript is often used to encompass writing JavaScript without frameworks or libraries. While many modern problems can be solved with frameworks and libraries, understanding what is available natively in JavaScript and how and when you can rely upon them will help you become a stronger developer.

Consider a scenario where you receive strings of text of varying length. Your goal is to count the number of occurrences of English vowels (“a”, “e”, “i”, “o”, and “u”) - capital and lowercase - contained in the strings.

JavaScript contains 3 vowels. DigitalOcean contains 6 vowels. Rhythms contains 0 vowels.

In this article, you will build a solution using an iterative loop and a second solution using regular expressions.

Prerequisites

If you would like to follow along with this article, you will need:

  • A modern web browser with a web developer console or a sandbox environment with a REPL implementation.
  • Familarity with loops, Strings, and Arrays will be beneficial.
  • Some familiarity with regular expressions may be beneficial but is not required.

This example uses for…of and includes() which is not supported in legacy browsers.

Using an Iterative Loop

In the iterative approach, you will loop through each letter of the string passed and then check to see if any of the letters match any of the vowels. If the letter matches the known possible values for vowels, you will increment a counter variable. Once the loop is complete, you can reference this variable and it will display the number of vowels.

Take a moment to think about how you would break down the requirements and steps of this task.

Now, using either the web developer console in a web browser or another implementation of a REPL, let’s build a solution for this problem.

First, let’s define what you know:

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

This code declares a constant - vowels - which contains an array of the five English vowels.

Then, let’s create a function that is passed a text value:

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

function countVowelsIterative(text) {

}

Inside of this function, you initialize a counter variable to 0.

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

function countVowelsIterative(text) {
  let counter = 0

  console.log(`The text contains ${counter} vowel(s)`)

  return counter
}

This code will log a message to the console and also return the value of the counter variable.

Next, to loop through the string, you can use a for…of loop:

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

function countVowelsIterative(text) {
  let counter = 0

  for (let letter of text.toLowerCase()) {

  }

  console.log(`The text contains ${counter} vowel(s)`)

  return counter
}

A for…of loop iterates over iterable objects - strings, arrays, maps, sets, and so on.

This code also converts all the characters in text to lowercase. There may be other scenarios where it is necessary to be case-sensitive, but for this particular scenario, you can utilize toLowerCase() and avoid having to also define capitalized vowels.

Then, you can use an if statement to check whether a letter matches any of vowels:

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

function countVowelsIterative(text) {
  let counter = 0

  for (let letter of text.toLowerCase()) {
    if (vowels.includes(letter)) {

    }
  }

  console.log(`The text contains ${counter} vowel(s)`)

  return counter
}

This code uses the includes() method on the array of vowels to determine whether the array includes the selected letter, returning true or false, as appropriate.

Finally, if the condition is true, you can increment the counter variable:

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

function countVowelsIterative(text) {
  let counter = 0

  for (let letter of text.toLowerCase()) {
    if (vowels.includes(letter)) {
      counter++
    }
  }

  console.log(`The text contains ${counter} vowel(s)`)

  return counter
}

Consider the possible values for text that a user might submit and ensure your function handles each appropriately.

An empty string:

countVowelsIterative('')

Which you expect should return a value of 0:

Output
The text contains 0 vowel(s)

A string with no vowels:

countVowelsIterative('Rhythms')

Which you expect should return a value of 0:

Output
The text contains 0 vowel(s)

And a string with one or more vowels:

countVowelsIterative('DigitalOcean')

Which you expect should return a numeric value equal to the number of occurrences of vowels in the string:

Output
The text contains 6 vowel(s)

You have succeeded in developing an iterative loop solution for counting the number of occurrences of English vowels in a string of text.

Using Regular Expressions

Regular expressions (regex) help you find patterns or character combinations within strings.

For this particular scenario, a regular expression would be well-suited to count the number of occurrences of English vowels in a string of text.

Regular expressions are available in many programming languages and used to solve many problems that require searching, matching, and filtering. Becoming familiar with regular expressions will add one more powerful tool to your developer skills.

Take a moment to think about how you would break down the requirements and steps of this task.

Now, using either the web developer console in a web browser or another implementation of a REPL, let’s build a solution for this problem.

Let’s create a function that is passed a text value:

function countVowelsRegex(text) {

}

Instead of an array containing vowels, you can use a regular expression with the pattern [aeiou]:

/[aeiou]/gi

For simple patterns, regular expressions are usually defined within a pair of slashes (/). The square brackets ([ and ]) are used to designate a “character class”. The regular expression will search for any character that matches within this character class.

After the closing slash, the letters g and i are used. A regular expression will stop after the condition is satisfied. Using g for a global search will continue to perform additional searches. Using i for a case-insensitive search allows you to avoid also having to define capitalized vowels.

Then, apply a regular expression to text:

function countVowelsRegex(text) {
  let matchingInstances = text.match(/[aeiou]/gi);
}

This code uses the match() method.

If there is a match, all the instances of that match the regular expression will be returned. If there is no match, a null value is returned.

Check to see if the matchingInstances value exists and handle both cases:

function countVowelsRegex(text) {
  let matchingInstances = text.match(/[aeiou]/gi);

  if (matchingInstances) {
    console.log(`The text contains ${matchingInstances.length} vowel(s)`)

    return matchingInstances.length
  } else {
    return 0
  }
}

If matchingInstances evaluates to a truthy value (that is, an array of matches found), you log a formatted message showing the number of vowels which is the same as the length of the array. Then, you return the number.

If matchingInstances evaluates to a falsy value, you return 0 as it means no matches were found.

Consider the possible values for text that a user might submit and ensure your function handles each appropriately.

A string with one or more vowels:

countVowelsRegex('DigitalOcean')

Which you expect should return a numeric value equal to the number of occurrences of vowels in the string:

Output
The text contains 6 vowel(s)

You have succeeded in developing a regular expression solution for counting the number of occurrences of English vowels in a string of text.

Conclusion

In this article, you successfully implemented two solutions that count the number of vowels in a string of text in JavaScript. In this process of devising the solutions, you broke the problem down into small steps and leveraged methods available in JavaScript.

The iterative loop approach used Strings, Arrays, for…of, toLowerCase(), if, includes(), and increment.

The regular expression approach used Strings, Arrays, match(), if…else, and length().

Choosing a solution for your project will require considering factors like readability and performance optimization.

Continue your learning by exploring other methods available for Strings and Arrays.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Philip Obosi

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel