How to format phone number in javascript

posted 1 min read

Formatting phone numbers in JavaScript is essential for creating clean, user-friendly inputs and displaying consistent contact information across your application. A typical approach involves stripping out non-numeric characters and then reformatting the digits to match a desired pattern, such as the standard U.S. format. Here's a simple example:

    function formatPhoneNumber(number) {
      const cleaned = ('' + number).replace(/\D/g, '');
      const match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/);
      if (match) {
        return `(${match[1]}) ${match[2]}-${match[3]}`;
      }
      return number;
    }

console.log(formatPhoneNumber("123-456-7890")); // (123) 456-7890

This function removes all non-digit characters and formats the number as (123) 456-7890 if it contains exactly 10 digits. For more advanced formatting, including handling international numbers and edge cases, refer to this comprehensive guide on JavaScript phone number formatting at MildDev—it covers everything from basic patterns to using libraries like libphonenumber-js for robust validation and formatting.

If you read this far, tweet to the author to show them you care. Tweet a Thanks
0 votes
0 votes

More Posts

How to Maintain Fast Load Time in Angular Apps

Sunny - Jun 18

The Power of Higher Order Functions in JavaScript: Writing Cleaner and More Efficient Code

Mubaraq Yusuf - Mar 19

Debouncing in JavaScript: A Must-Know Technique for Developers

Mubaraq Yusuf - Feb 15

Understanding Obfuscation In Javascript

Dhanush Nehru - Jan 12

A Practical guide to Async and Await for JavaScript Developers

Mubaraq Yusuf - Jan 8
chevron_left