Open In App

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

Last Updated : 25 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads