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.

0 votes
0 votes

More Posts

I’m a Senior Dev and I’ve Forgotten How to Think Without a Prompt

Karol Modelskiverified - Mar 19

How I Built a React Portfolio in 7 Days That Landed ₹1.2L in Freelance Work

Dharanidharan - Feb 9

Your Tech Stack Isn’t Your Ceiling. Your Story Is

Karol Modelskiverified - Apr 9

5 Web Dev Pitfalls That Are Silently Killing Your Projects (With Real Fixes)

Dharanidharan - Mar 3

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10
chevron_left

Related Jobs

View all jobs →

Commenters (This Week)

3 comments
2 comments
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!