frontend/lib/phoneNumbers.tsx (view raw)
1import {
2 CountryIso2,
3 defaultCountries,
4 getActiveFormattingMask,
5 parseCountry,
6} from 'react-international-phone';
7
8export const getFormatedPhoneNumber = ({
9 phone,
10 phoneCountry,
11}: {
12 phone: string;
13 phoneCountry: CountryIso2;
14}): string => {
15 if (!phoneCountry || phoneCountry === '') return phone;
16 const parsedCountry = parseCountry(
17 defaultCountries.find(country => country[1] === phoneCountry)
18 );
19 const activeMask = getActiveFormattingMask({phone, country: parsedCountry});
20 const regex = new RegExp(`\\+(${parsedCountry.dialCode})?0?`);
21 let splittedPhone = phone.replace(regex, '').split('');
22
23 const maskWithValues = activeMask
24 .split('')
25 .map(char => (char === '.' ? splittedPhone.shift() : char))
26 .join('');
27
28 return `+${parsedCountry.dialCode} ${maskWithValues}`;
29};