Skip to content
the poor coder

count vowels in a string javascript

Poor Man
Published
Reading time
1 min read
On this page

Count Vowels in a String using Javascript#

Counting the number of vowels in a given string is a common task in programming. In Javascript, we can do this by looping through each character in the string and checking if it is a vowel or not.

Method 1:#

One way to count vowels in a string is to use a regular expression to match all the vowels and then count the number of matches.

JavaScript

function countVowels(str) {
  return (str.match(/[aeiou]/gi) || []).length;
}
  • str.match(/[aeiou]/gi) matches all the vowels in the string.
  • (str.match(/[aeiou]/gi) || []) returns an array of matches or an empty array if there are none.
  • (str.match(/[aeiou]/gi) || []).length returns the length of the array, which is the number of vowels in the string.

Method 2:#

Another way to count vowels in a string is to loop through each character in the string and check if it is a vowel.

JavaScript

function countVowels(str) {
  var count = 0;
  for (var i = 0; i < str.length; i++) {
    if (/[aeiou]/.test(str[i])) {
      count++;
    }
  }
  return count;
}
  • var count = 0; initializes a variable to keep track of the number of vowels.
  • for (var i = 0; i < str.length; i++) loops through each character in the string.
  • if (/[aeiou]/.test(str[i])) checks if the current character is a vowel.
  • count++; increments the count if the current character is a vowel.
  • return count; returns the total number of vowels in the string.

Usage:#

To use the function, simply call it with a string as an argument:

JavaScript

var str = "Hello World";
var vowels = countVowels(str);
console.log(vowels); // output: 3

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC