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") => 0

Solution

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.
  • g flag → global (sabhi matches, sirf pehla nahi).
  • i flag → 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 → null return.

Part 3: Safe length access

  • ?.length ?? 0
  • ?. → optional chaining:
  • Agar .match() ne array return kiya → .length access karo.
  • Agar .match() ne null return kiya → undefined return (error nahi).
  • ?? 0 → nullish coalescing:
  • Agar ?.length undefined hai (null case) → 0 return.
  • 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.