Exercise 2: Mask Phone Number

Problem Statement

Function `maskPhone(phone)` banao jo last 4 digits visible रखे, बाकी `*`. Example: "9876543210" → "******3210"

Sample Output:

maskPhone("9876543210") => "******3210"
maskPhone("+91-98765-43210") => "******3210"

Solution

const maskPhone = (phone) => {
  const s = String(phone ?? '').replace(/\\D/g, '');
  const last4 = s.slice(-4);
  return last4 ? '*'.repeat(Math.max(0, s.length - 4)) + last4 : '';
};

Explanation

Overall Goal:

  • Phone number ko mask karna: last 4 digits visible, baaki stars.
  • Privacy protection: sensitive data hide karna.

Line 1: Function header

  • const maskPhone = (phone) => { → function jo phone number lega.

Line 2: Extract digits only

  • const s = String(phone ?? '').replace(/\\D/g, '');
  • String(phone ?? '') → nullish coalescing: null/undefined ho to empty string.
  • .replace(/\\D/g, '') → regex replace:
  • \\D → non-digit characters (D = NOT digit).
  • /g → global flag (sabhi matches).
  • '' → replace with empty (remove).
  • Example: "+91-98765-43210""919876543210".

Line 3: Get last 4 digits

  • const last4 = s.slice(-4);
  • .slice(-4) → negative index: end se 4 characters.
  • Example: "9876543210""3210".

Line 4: Create masked string

  • return last4 ? '*'.repeat(Math.max(0, s.length - 4)) + last4 : '';
  • last4 ? ... : '' → ternary: agar last4 hai to mask, warna empty.
  • Math.max(0, s.length - 4) → stars ki count:
  • Agar length < 4 → 0 stars (edge case handle).
  • Agar length >= 4 → length - 4 stars.
  • '*'.repeat(...) → stars repeat karo.
  • + last4 → stars ke baad last4 digits add karo.
  • Example: "9876543210""******3210".

Real world:

  • Payment forms: credit card, phone number masking.
  • User profiles: sensitive info hide karna.
  • Error logs: PII (Personally Identifiable Information) mask karna.