Saturday, August 30, 2025
HomeLanguagesJavascriptHow to format a phone number in Human-Readable using JavaScript ?

How to format a phone number in Human-Readable using JavaScript ?

Give a phone number and the task is to format a phone number in such a way that it becomes easy to understand for humans.

There are two approaches to format the numbers which are discussed below: 

  • Using RegExp
  • Using substr() Method

Approach 1: Using RegExp

  • A RegExp is used to replace the original phone number with a human-readable phone number.
  • The RegExp is searching for the 3 digits and saves it in a variable($1 for the first 3 digits, $2 for the second 3 digits, and so on.)
  • In the end, It is just concatenating them with ‘-‘ among them.

Example: This example implements the above approach. 

Javascript




const phoneNo = '4445556678';
 
function formatNumber() {
    console.log( phoneNo
        .replace( /(\d{3})(\d{3})(\d{4})/,
        '$1-$2-$3' )
    );
}
 
formatNumber();


Output

444-555-6678

Approach 2: Using substr() Method

  • This example is using the substr() method to format a phone number in Human-Readable format.
  • It is taking a substrings of length 3 and putting ‘-‘ among them. Remaining string elements using the same method.

Example: This example implements the above approach. 

Javascript




const phoneNo = '4445556678';
 
function formatNumber() {
    const formatNum = phoneNo.substr(0, 3) + '-' +
                      phoneNo.substr(3, 3) + '-' +
                      phoneNo.substr(6, 4);
 
    console.log(formatNum);
}
 
formatNumber();


Output

444-555-6678

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!
RELATED ARTICLES

Most Popular

Dominic
32249 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6617 POSTS0 COMMENTS
Nicole Veronica
11792 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11838 POSTS0 COMMENTS
Shaida Kate Naidoo
6731 POSTS0 COMMENTS
Ted Musemwa
7012 POSTS0 COMMENTS
Thapelo Manthata
6689 POSTS0 COMMENTS
Umr Jansen
6701 POSTS0 COMMENTS