Skip to content

Dave Helgerson

Salesforce Software Development and Consulting

Menu
  • Contact
  • Resume
Menu

Re-format a Phone Number using Apex

December 29, 2013

Below is a static method that will reformat a phone number. The method removes characters, and it will check for strings of numbers that are 10 or 11 digits long. The logic would need to be changed to process international numbers.

private static String FormatPhone(String Phone) {
  string nondigits = '[^0-9]';
  string PhoneDigits;
  
  // remove all non numeric
  PhoneDigits = Phone.replaceAll(nondigits,'');
  
  // 10 digit: reformat with dashes
  if (PhoneDigits.length() == 10) 
    return PhoneDigits.substring(0,3) + '-' +
           PhoneDigits.substring(3,6) + '-' +
           PhoneDigits.substring(6,10);
  // 11 digit: if starts with 1, format as 10 digit 
  if (PhoneDigits.length() == 11) {
    if (PhoneDigits.substring(0,1) == '1') {
      return  PhoneDigits.substring(1,4) + '-' +
              PhoneDigits.substring(4,7) + '-' +
              PhoneDigits.substring(7,11);
    }
  }

  // if it isn't a 10 or 11 digit number, return the original because
  // it may contain an extension or special information
  return( Phone );
}

Related

1 thought on “Re-format a Phone Number using Apex”

  1. Justin Urbaniak says:
    February 19, 2016 at 2:36 pm

    Perfect Tutorial. Helped me fix my problem

Comments are closed.

Super Clone Pro
© 2023 Dave Helgerson | Powered by Minimalist Blog WordPress Theme