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]/gimatches all vowels (both uppercase and lowercase).match()returns an array of matches, or null if none.|| []ensures no error when match returns null..lengthgives 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
vowelsstring. - 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
Post a Comment