How to useRegExp in Javascript

  • 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

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

Similar Reads

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....

Approach 2: Using substr() Method

...

Contact Us