Day 9 – Count Vowels in a String using JavaScript | DSA Challenge with Code & Explanation

 

๐Ÿง  Day 9: Count Vowels in a String – JavaScript Interview Prep

Welcome to Day 9 of the #CodeWithJaffer JavaScript DSA series! Today, we’ll solve a popular string-based interview problem: “Count the number of vowels in a given string.”

๐Ÿ” Problem Statement:

Write a JavaScript function that takes a string as input and returns the count of vowels (a, e, i, o, u) present in it.

✅ Example Input & Output:


// Input:
"CodeWithJaffer"

// Output:
5 vowels (o, e, i, a, e)

๐Ÿ’ก Method 1: Using RegEx


function countVowels(str) {
  return (str.match(/[aeiou]/gi) || []).length;
}

✅ Explanation:

  • /[aeiou]/gi matches all vowels (both uppercase and lowercase).
  • match() returns an array of matches, or null if none.
  • || [] ensures no error when match returns null.
  • .length gives the count of vowels.

๐Ÿ’ก Method 2: Using For-Loop


function countVowelsLoop(str) {
  let count = 0;
  const vowels = "aeiouAEIOU";
  for (let char of str) {
    if (vowels.includes(char)) {
      count++;
    }
  }
  return count;
}

✅ Explanation:

  • Iterates over each character.
  • Checks if it’s present in the vowels string.
  • Increments count for every vowel match.

๐ŸŽฏ Output:


console.log(countVowels("CodeWithJaffer")); // ➡️ 5
console.log(countVowelsLoop("CodeWithJaffer")); // ➡️ 5

๐Ÿ“Œ Tips to Remember:

  • Use regex for cleaner and faster solutions.
  • Use loops when regex is restricted in interviews.
  • Don’t forget to handle uppercase vowels.

#CodeWithJaffer | Stay consistent, keep practicing. Share your solution in comments below ๐Ÿ‘‡

๐Ÿ”– Labels/Tags:

JavaScript, DSA, Interview Prep, Coding Challenge, Frontend, Vowels in String, CodeWithJaffer

Comments

Popular posts from this blog

Day 4 – Palindrome Number in JavaScript Without Converting to String

Day 13: Find Missing Number in an Array – JavaScript DSA Challenge