«

»

Oct 30

Format Phone Numbers in JavaScript

Here is a quick function that will grab any group of integers from a string so you may format phone numbers (or any number based formatting) quickly. By default this function formats phone numbers in standard 7 digit or 10 digit formatting. Example: 123-4567 and (123) 456-7890. The function matches all digits from a string. If a grouped match is found it checks the group length for the proper amount of numbers. If only one match is found it checks the single match for the length to determine if it is 7 or 10 digit. This can be easily modified to include country codes or a different string format if necessary. Hope this helps.

function FormatPhoneNumber(num) {
	var str = num.toString();
	
	var matched = str.match(/\d+\.?\d*/g);

	// 10 digit
	if (matched.length === 3) {
		return '(' + matched[0] + ') ' + matched[1] + '-' + matched[2];
	// 7 digit
	} else if (matched.length === 2) {
		return matched[0] + '-' + matched[1];
	}
	// no formatting attempted only found integers (i.e. 1234567890)
	else if (matched.length === 1) {
		// 10 digit
		if (matched[0].length === 10) {
			return '(' + matched[0].substr(0, 3) + ') ' + matched[0].substr(3, 3) + '-' + matched[0].substr(6);
		}
		// 7 digit
		if (matched[0].length === 7) {
			return matched[0].substr(0, 3) + '-' + matched[0].substr(3);
		}
	}
	
	// Format failed, return number back
	return num;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>