Exercise 14: Format Phone Number (Indian Format)

Problem Statement

Create a function `formatPhone(phone)` that converts a 10-digit number to Indian format. Example: formatPhone("9876543210") → "+91 98765 43210"

Sample Output:

formatPhone("9876543210") => "+91 98765 43210"
formatPhone("+91-98765-43210") => "+91 98765 43210"

Solution

const formatPhone = (phone) => {
  const digits = String(phone ?? "").replace(/\D/g, "");
  if (digits.length !== 10) return phone;
  return `+91 ${digits.slice(0, 5)} ${digits.slice(5)}`;
};

Explanation

Overall Goal:

  • 10-digit phone number ko formatted string me convert.
  • Indian country code (+91) add karna.

Line 1: Function header

  • const formatPhone = (phone) => {

Line 2: Extract digits

  • const digits = String(phone ?? "").replace(/\D/g, "");
  • Non-digits remove karke sirf numbers extract.

Line 3: Validate length

  • if (digits.length !== 10) return phone;
  • Invalid length ho to original return.

Line 4: Format

  • return +91 ${digits.slice(0, 5)} ${digits.slice(5)};
  • First 5 digits, space, last 5 digits.

Real world:

  • Contact forms: phone number display.
  • User profiles: formatted phone display.
  • SMS integration: phone number formatting.