You can use a simple helper method that will take a string, sterilize the input to remove spaces or unwanted special characters used as a delimiter, and then use the built-in ToString method. If you check different lengths, you can also make sure that the format comes out as you see fit. For instance:
public string FormatPhoneNumber(string phoneNumber)
{
string originalValue = phoneNumber;
phoneNumber= new System.Text.RegularExpressions.Regex(@"\D")
.Replace(phoneNumber, string.Empty);
value = value.TrimStart('1');
if (phoneNumber.Length == 7)
return Convert.ToInt64(value).ToString("###-####");
if (phoneNumber.Length == 9)
return Convert.ToInt64(originalValue).ToString("###-###-####");
if (phoneNumber.Length == 10)
return Convert.ToInt64(value).ToString("###-###-####");
if (phoneNumber.Length > 10)
return Convert.ToInt64(phoneNumber)
.ToString("###-###-#### " + new String('#', (phoneNumber.Length - 10)));
return phoneNumber;
}
source
share