Jerry Nixon @Work: Format Phone Numbers

Jerry Nixon on Windows

Tuesday, December 6, 2011

Format Phone Numbers

This is a simple requirement: the user types in some string that should be a phone number. You need to format that string to look nice and neat. Assuming that we are in the United States where there are 10 digit numbers and a country code of +1, here’s the solution:


In the code above we remove everything that is not a number. Then we strip the country code. Then we have to handle different lengths. Only lengths of 7 and 10 are truly valid. Greater than 10, we assume it is an extension and we format it as such.

Get the code here.

The output should look something like this:


I hope this helps you while you are developing. Best of luck!