Re-format a Phone Number using Apex

29 Dec

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 );
}

One Reply to “Re-format a Phone Number using Apex”

Comments are closed.