Write a JavaScript program to count vowels in a string

Description: Count the vowels in “Tutorials Class”.

Hint:

  • Vowels are a, e, i, o and u.
  • match() with the g flag returns all matches, or null if none.

JavaScript program to count vowels

const text = "Tutorials Class";
const matches = text.toLowerCase().match(/[aeiou]/g);

console.log("Vowels:", matches ? matches.length : 0);

Output:

Tutorials Class - Output Window

Vowels: 5

How it works

  • /[aeiou]/g finds every vowel.
  • If there is no vowel, match() returns null, so we check it first.

Read Regular Expressions.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.