JAVASCRIPT

Format Phone Numbers with Hyphens

Learn to automatically format raw 10-digit phone number strings by inserting hyphens, making them more readable for users.

function formatPhoneNumber(phoneNumber) {
  const cleanNum = phoneNumber.replace(/\\D/g, ''); // Remove all non-digits
  const phoneRegex = /^(\\d{3})(\\d{3})(\\d{4})$/;

  if (phoneRegex.test(cleanNum)) {
    return cleanNum.replace(phoneRegex, '($1) $2-$3');
  } else {
    return cleanNum; // Return cleaned number if format doesn't match
  }
}

console.log(formatPhoneNumber("1234567890")); // "(123) 456-7890"
console.log(formatPhoneNumber(" (123) 456-7890 ")); // "(123) 456-7890"
console.log(formatPhoneNumber("+1-123-456-7890")); // "(123) 456-7890"
console.log(formatPhoneNumber("555")); // "555"
How it works: This snippet provides a JavaScript function `formatPhoneNumber` that takes a string, first cleans it by removing all non-digit characters, and then uses a regular expression to reformat a 10-digit number into a more readable `(XXX) XXX-XXXX` pattern. It leverages capturing groups in the regex and the `replace` method's ability to use these groups in the replacement string, which is highly useful for standardizing user input.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs