w3resource

JavaScript: Count the number of vowels in a given string

JavaScript Basic: Exercise-54 with Solution

Write a JavaScript program to count the number of vowels in a given string.

Pictorial Presentation:

JavaScript: Count the number of vowels of a given string

Sample Solution:

HTML Code:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JavaScript program to count the number of vowels in a given string.</title>
</head>
<body>

</body>
</html>

JavaScript Code:

function vowel_Count(str)
{ 

  return str.replace(/[^aeiou]/g, "").length; 
}

console.log(vowel_Count("Python"));
console.log(vowel_Count("w3resource.com"));

Sample Output:

1
5

Flowchart:

Flowchart: JavaScript - Count the number of vowels in a given string

ES6 Version:

function vowel_Count(str)
{ 

  return str.replace(/[^aeiou]/g, "").length; 
}

console.log(vowel_Count("Python"));
console.log(vowel_Count("w3resource.com"));

Live Demo:

See the Pen JavaScript - count the number of vowels in a given string - basic-ex-54 by w3resource (@w3resource) on CodePen.


Contribute your code and comments through Disqus.

Previous: Write a JavaScript program to check if the characters a and b are separated by exactly 3 places anywhere (at least once) in a given string.
Next: Write a JavaScript program to check if a given string contains equal number of p's and t's present.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

JavaScript: Tips of the Day

Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters)

Example:

const isAnagram = (str1, str2) => {
  const normalize = str =>
    str
      .toLowerCase()
      .replace(/[^a-z0-9]/gi, '')
      .split('')
      .sort()
      .join('');
  return normalize(str1) === normalize(str2);
};
console.log(isAnagram('iceman', 'cinema')); // true

Output:

true