Emil
Emil

Reputation: 15

Phone number format javascript

I'm trying to format some phone numbers with regexp. The phone numbers i have stored are of diffrent length and all phone numbers have their country codes. Lets say a number looks like this: 00460708186681. I want that one to be formatted as: +46 (0)708-18 66 81. The first three groups are easy:

/00([\d]{2})([\d]{1})([\d]{3})/

Because the beginning of the number will always be the same. It's the last part where i dont know the length of the remaining chars (and i want them to be divided into groups of two).

Upvotes: 1

Views: 1937

Answers (4)

Leonel Kahameni
Leonel Kahameni

Reputation: 933

Here is an example of code done in TypeScript, but you can surely parse it into JavaScript:

const formatPhoneNumber = (phoneNumber: number, format?: string, code?: boolean): string => {
  let _format = format === undefined ? '---  ---  ---' : format
  let x = 1
  const newFormat = _format.replace(/-+/g, () => '$' + x++)
  let regex = '^'
  _format.match(/-+/g)?.forEach((c, k) => {
      regex += `(\\d{${c.length}})?`
  })
  return (code !== undefined && code === true ? '+' : '') + (phoneNumber.toString().concat(_format.split(' ').join(''))).slice(0, _format.split(' ').join('').length).toString().replace(new RegExp(regex, 'g'), newFormat)}

To test it, you can do:

const formatedPhoneNumber = formatPhoneNumber(600000000) // => 600  000 000
const formatedPhoneNumberWithCountryCode = formatPhoneNumber(237600000000, 'xxx xxx xxx xxx', true) // => +237 600 000 000

This example is perfectly modular, so you can do specify your own format (template) to have a different output!

Note: I'm Cameroonian, that's why I used that strange template, Feel free to adapt the template to the needed phone number template

Upvotes: 0

gaurang171
gaurang171

Reputation: 9080

Here is solution :

Javascript:

var num="00460708186681";
var res=num.replace(/([0+]{2})([1-9]{2})([\d]{1})([\d]{3})([\d]{2})([\d]{2})([\d]{2})/g,'+$2($3)-$4 $5 $6 $7');
alert(res);

Try above script on http://codebins.com/

Upvotes: 0

Bergi
Bergi

Reputation: 664185

Regex is not the best solution here. Use this:

var num = new String("00460708186681"),
    i = 2,
    p,
    res = "+"+num.substr(i,2)+" ("+num.charAt(i+=2)+")"+num.substr(++i,3)+"-"+num.substr(i+=3,2);
while (p=num.substr(i+=2,2))
    res+= "\u00A0"+p;
return res;

Which will work for infinitely long numbers. A regex can't do that.

Upvotes: 1

Vala
Vala

Reputation: 5674

Start with the following regex as your base:

00(\d{2})(\d)(\d{3})(\d{2})

Now add another pair (\d{2})? (note the '?') for every pair it's possible to have. So if the maximum number of pairs is 3, you do the following:

00(\d{2})(\d)(\d{3})(\d{2})(\d{2})?(\d{2})?

It's not pretty, but you need to do it that way in order to get them grouped correctly. Or you could simply do:

00(\d{2})(\d)(\d{3})((?:\d{2}){2,4}) // In this case it's 2 to 4 pairs of digits on the end.

To match the string, then you can manually add spaces in the last group which will contain all the digits after your initial formatting.

Upvotes: 1

Related Questions