Exercise 3: Count Words (robust)
Problem Statement
Create a function `wordCount(text)` that handles multiple spaces/newlines and returns word count.
Sample Output:
wordCount("Hello World") => 2
wordCount(" Multiple Spaces ") => 2
wordCount("") => 0Solution
const wordCount = (text) => {
const s = String(text ?? '').trim();
return s ? s.split(/\\s+/).length : 0;
};Explanation
Overall Goal:
- Text me words count karna, multiple spaces/newlines handle karke.
- Robust solution: edge cases handle karna.
Line 1: Function header
const wordCount = (text) => {→ function jo text lega.
Line 2: Normalize string
const s = String(text ?? '').trim();String(text ?? '')→ nullish coalescing: null/undefined ho to empty string..trim()→ start aur end se spaces remove.- Example:
" Hello World "→"Hello World".
Line 3: Count words
return s ? s.split(/\\s+/).length : 0;s ? ... : 0→ ternary: agar string non-empty hai to count, warna 0.s.split(/\\s+/)→ regex split:\\s+→ one or more whitespace characters (space, tab, newline)..split()→ array return karta hai jisme words hote hain..length→ array ki length = words ki count.- Example:
"Hello World"→ split →["Hello", "World"]→ length 2. - Example:
""→ empty → return 0.
Real world:
- Blog editor: character/word count display.
- Textarea counters: Twitter-style character limits.
- Content analysis: article length check.