How to Format Phone Numbers in JavaScript
It’s a good idea to format your phone numbers properly in JavaScript. It makes your web app more readable. Contact information is also the type of thing you generally want to keep consistent. This guide walks you through how to do that. We’ll use the standard US phone number format as an example.
What is the typical phone number format?
A typical US phone number format is (XXX) XXX-XXXX
, where X
represents a digit. Our goal is to convert a string of numbers, like 1234567890
, into this readable format.
How to create a JavaScript function to format a phone number?
The following JavaScript function takes a string of digits and formats it into the US phone number format:
function formatPhoneNumber(phoneNumberString) { var cleaned = ('' + phoneNumberString).replace(/\\D/g, ''); var match = cleaned.match(/^(\\d{3})(\\d{3})(\\d{4})$/); if (match) { return '(' + match[1] + ') ' + match[2] + '-' + match[3]; } return null; }
How it works
- Clean the input: We start by removing any non-digit characters from the input string. This is done using
.replace(/\\D/g, '')
, where\\D
matches any character that is not a digit. - Match parts: We then use
.match()
to capture three groups of digits using a regular expression. The expression^(\\d{3})(\\d{3})(\\d{4})$
looks for three sequences of digits, each of specific lengths corresponding to the parts of a US phone number. - Format and return: If the input string matches the pattern, we format it by inserting parentheses and a dash in the appropriate places. If the input does not match (e.g., it has too few or too many digits), the function returns
null
.
Example
Here's how you can use the formatPhoneNumber
function:
const phoneNumber = '1234567890'; const formattedNumber = formatPhoneNumber(phoneNumber); console.log(formattedNumber); // Outputs: (123) 456-7890
This approach ensures your application can handle phone numbers in a consistent format, improving data quality and user experience. For more advanced use cases, such as international number formatting, consider leveraging libraries like Google's libphonenumber. But this function will suffice for a good chunk of web apps.
Invite only
We're building the next generation of data visualization.
How to Remove Characters from a String in JavaScript
Jeremy Sarchet
How to Sort Strings in JavaScript
Max Musing
How to Remove Spaces from a String in JavaScript
Jeremy Sarchet
Detecting Prime Numbers in JavaScript
Robert Cooper
How to Parse Boolean Values in JavaScript
Max Musing
How to Remove a Substring from a String in JavaScript
Robert Cooper