Saturday, November 16, 2024
Google search engine
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

Recent Comments