UNPKG

@sinchsmb/ui-kit

Version:

UI kit for SinchSMB frontend

40 lines (32 loc) 1.07 kB
import { useMemo } from 'react'; import { COUNTRIES_PHONE_CODES } from '../../../constans/countriesPhoneCodes'; import { countryForPhone } from '../../utils/countryForPhone'; /** * Phone number formatting function */ export type FormattedPhoneNumber = (phoneNumber?: string) => string; /** * Returns the function for phone number formatting * * @example * const formatPhoneNumber = useFormattedPhoneNumber(); * formatPhoneNumber('+12345678900'); // +1 234 567 8900 * formatPhoneNumber('+61312312312'); // +61 312 312 312 * formatPhoneNumber('1234'); // 1234 */ export function useFormattedPhoneNumber(): FormattedPhoneNumber { return useMemo<FormattedPhoneNumber>(() => { return (phone) => { if (!phone) { return ''; } const country = countryForPhone(phone); if (country) { const phoneCode = COUNTRIES_PHONE_CODES[country]; const regexp = new RegExp(`(\\${phoneCode})(\\d{3})(\\d{3})(\\d+)`, 'ig'); return phone.replace(regexp, '$1 $2 $3 $4'); } return phone; }; }, []); }