Exercise 5: Count Vowels in Text
Problem Statement
Create a function `countVowels(text)` that counts vowels (a,e,i,o,u) case-insensitive.
Sample Output:
countVowels("Hello") => 2
countVowels("JavaScript") => 3
countVowels("xyz") => 0Solution
const countVowels = (text) => (String(text ?? '').match(/[aeiou]/gi)?.length ?? 0);Explanation
Overall Goal:
- Text me vowels (a, e, i, o, u) count karna, case-insensitive.
- Example: "Hello" → 2 vowels (e, o).
Single Line Solution:
const countVowels = (text) => (String(text ?? '').match(/[aeiou]/gi)?.length ?? 0);
Part 1: String conversion
String(text ?? '')text ?? ''→ nullish coalescing: null/undefined ho to empty string.String(...)→ guarantee karta hai ki result string hi hoga.
Part 2: Regex matching
.match(/[aeiou]/gi)/[aeiou]/gi→ regex pattern:[aeiou]→ character class: a, e, i, o, u me se koi bhi.gflag → global (sabhi matches, sirf pehla nahi).iflag → case-insensitive (A, E, I, O, U bhi match honge)..match()→ array return karta hai jisme sabhi matches hote hain:"Hello".match(/[aeiou]/gi)→["e", "o"]- Agar koi match nahi →
nullreturn.
Part 3: Safe length access
?.length ?? 0?.→ optional chaining:- Agar
.match()ne array return kiya →.lengthaccess karo. - Agar
.match()nenullreturn kiya →undefinedreturn (error nahi). ?? 0→ nullish coalescing:- Agar
?.lengthundefinedhai (null case) →0return. - Agar length mila → wahi return.
Real world:
- Text analysis: content me vowels count karna.
- Language processing: vowel density calculate karna.
- Word games: vowels find karna.