Open In App

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: 



Approach 1: Using RegExp

Example: This example implements the above approach. 




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

Example: This example implements the above approach. 




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


Article Tags :