const hasLetters = (value: string) => Boolean(value.match(/[a-zA-Z]/)) const hasPunctuations = (value: string) => Boolean(value.match(/[^a-zA-Z0-9\(\)\-\ .+]/)) const getNumbersOnly = (value: string) => value.replace(/\D/g, '') const parsePhoneNumber = (value: string) => (getNumbersOnly(value).match(/(\d{0,1})\ {0,1}(\d{3})(\d{7})$/) || []).slice(1) export const clean = (phoneNumber: string): string => { const [countryCode, areaCode, exchangeCode] = parsePhoneNumber(phoneNumber) if (hasLetters(phoneNumber)) { throw new Error('Letters not permitted') } else if (hasPunctuations(phoneNumber)) { throw new Error('Punctuations not permitted') } else if (getNumbersOnly(phoneNumber).length > 11) { throw new Error('More than 11 digits') } else if (exchangeCode === undefined || areaCode === undefined) { throw new Error('Incorrect number of digits') } else if (countryCode && countryCode === '2') { throw new Error('11 digits must start with 1') } else if (countryCode && countryCode !== '1') { throw new Error('More than 11 digits') } else if (areaCode?.[0] === '0') { throw new Error('Area code cannot start with zero') } else if (areaCode?.[0] === '1') { throw new Error('Area code cannot start with one') } else if (exchangeCode === undefined || exchangeCode?.[0] === '0') { throw new Error('Exchange code cannot start with zero') } else if (exchangeCode?.[0] === '1') { throw new Error('Exchange code cannot start with one') } return `${areaCode}${exchangeCode}` }