One of the most common task we face while working is to format the phone number with javascript or Jquery.
Learn how you can effectively format the phone number in javascript.
Example
Input: 9809142333 Output: (980) 914-2333
Format phone number without country code
To format phone number properly we need to first make sure that the input is numeric and is not more than 10 numbers.
Now once we have our input ready we can format it in US phone format.
let formatPhoneNumber = (str) => { //Filter only numbers from the input let cleaned = ('' + str).replace(/\D/g, ''); //Check if the input is of correct length let match = cleaned.match(/^(\d{3})(\d{3})(\d{4})$/); if (match) { return '(' + match[1] + ') ' + match[2] + '-' + match[3] }; return null };
Input: console.log(formatPhoneNumber('9809142333')); console.log(formatPhoneNumber('98091sss42333')); Output: "(980) 914-2333" "(980) 914-2333"
This works great for input without country extension code. But if you want to format phone number with country extension code then we have to modify the function.
Format phone number with country code
let formatPhoneNumber = (str) => { //Filter only numbers from the input let cleaned = ('' + str).replace(/\D/g, ''); //Check if the input is of correct let match = cleaned.match(/^(1|)?(\d{3})(\d{3})(\d{4})$/); if (match) { //Remove the matched extension code //Change this to format for any country code. let intlCode = (match[1] ? '+1 ' : '') return [intlCode, '(', match[2], ') ', match[3], '-', match[4]].join('') } return null; }
Input: console.log(formatPhoneNumber('9809142333')); console.log(formatPhoneNumber('+19801542335')); Output: "(980) 914-2333" "+1 (980) 154-2335"