How to count the number of vowels in a string using JavaScript

In this shot, we'll learn how to count the number of vowels present in a string using JavaScript.

Problem statement

Given a string s, count the number of vowels present in s and print it.

We will define a countVowels function to solve this.

Parameters

The function countVowels takes a string as a parameter.

Returns

It returns 0 if no vowels are found in the given string. Otherwise, it returns the count of the vowels present in the given string.

Example

s = "The quick brown fox jumps over the lazy dog"

The number of vowels in the string s are 11. Let us see how we can get this number in JavaScript.

Code

//given string
var s = "The quick brown fox jumps over the lazy dog"
//function to count number of vowels in a string
function countVowels(s) {
//regex to get vowels
var c = s.match(/[aeiou]/gi);
return c === null ? 0 : c.length;
}
//call countVowels function
console.log(countVowels(s))

Explanation

  • Line 2: We initialize the string s and assign a value to it.
  • Line 5: We define the countVowels function, which accepts a string as a parameter and returns the count of the vowels present in that string.
  • Line 7: We will pass /[aeiou]/gi as a parameter to the match method, which checks and returns characters which are matching the pattern,/[aeiou]/gi, that is it returns an array of characters that are vowels.
  • Line 8: If no vowels are found we will get null so we check for null and return 0 else return the length of the array.
  • Line 12: We call the countVowels function and pass s as a parameter to it. We then print the returned value.

Free Resources