formatUsPhoneNumber static method

String formatUsPhoneNumber(
  1. String? phoneNumber
)

Formats a U.S. phone number

Implementation

static String formatUsPhoneNumber(String? phoneNumber)
{
  // Formatted value generated.
  StringBuffer sb = new StringBuffer();

  if (phoneNumber == null) {
    phoneNumber = ella.EMPTY_STRING;
  }

  if (phoneNumber.length == 11) {
    phoneNumber = phoneNumber.substring(1);
  }

  if (phoneNumber.isNotEmpty) {
    // Format areaCode.
    sb.write("(");

    String areaCode = phoneNumber.substring(0, Math.min(3, phoneNumber.length) );

    sb.write(areaCode);

    if (phoneNumber.length > 3) {
      sb.write(") ");
    }

    if (phoneNumber.length > 3) {
      // Format prefix.
      String prefix = phoneNumber.substring(3, Math.min(6, phoneNumber.length) );

      sb.write(prefix);

      if (phoneNumber.length > 6) {
        sb.write(" - ");
      }

      // Format lineNumber.
      if (phoneNumber.length > 6) {
        String lineNumber = phoneNumber.substring(6, Math.min(10, phoneNumber.length) );
        sb.write(lineNumber);
      }
    }
  }

  return sb.toString();
}