Created
August 26, 2022 12:30
-
-
Save ajsaraujo/39ac4fe019f396acccc49bb81bfe8143 to your computer and use it in GitHub Desktop.
Formatar número de telefone
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { formatPhoneNumber } from './format-phone-number'; | |
describe('formatPhoneNumber', () => { | |
it('deve formatar como XXXX-XXXX se tiver 8 dígitos', () => { | |
expect(formatPhoneNumber('12345678')).toEqual('1234-5678'); | |
}); | |
it('deve formatar como X XXXX-XXXX se tiver 9 dígitos', () => { | |
expect(formatPhoneNumber('912345678')).toEqual('9 1234-5678'); | |
}); | |
it('deve formatar como (XX) XXXX-XXXX se tiver 10 dígitos', () => { | |
expect(formatPhoneNumber('7912345678')).toEqual('(79) 1234-5678'); | |
}); | |
it('deve formatar como (XX) X XXXX-XXXX se tiver 11 dígitos', () => { | |
expect(formatPhoneNumber('79912345678')).toEqual('(79) 9 1234-5678'); | |
}); | |
it('deve formatar como +XX (XX) XXXX-XXXX se tiver 12 dígitos', () => { | |
expect(formatPhoneNumber('557912345678')).toEqual('+55 (79) 1234-5678'); | |
}); | |
it('deve formatar como +XX (XX) X XXXX-XXXX se tiver 13 dígitos', () => { | |
expect(formatPhoneNumber('5579912345678')).toEqual('+55 (79) 9 1234-5678'); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const formatPhoneNumber = (value: string) => { | |
const CODIGO_PAIS = 2; | |
const DDD = 2; | |
const DIGITO_OPCIONAL = 1; | |
const NUMERO = 8; | |
const replacers: Record<number, [RegExp, string]> = { | |
[NUMERO]: [/(\d{4})(\d{4})/, '$1-$2'], | |
[DIGITO_OPCIONAL + NUMERO]: [/(\d{1})(\d{4})(\d{4})/, '$1 $2-$3'], | |
[DDD + NUMERO]: [/(\d{2})(\d{4})(\d{4})/, '($1) $2-$3'], | |
[DDD + DIGITO_OPCIONAL + NUMERO]: [ | |
/(\d{2})(\d{1})(\d{4})(\d{4})/, | |
'($1) $2 $3-$4', | |
], | |
[CODIGO_PAIS + DDD + NUMERO]: [ | |
/(\d{2})(\d{2})(\d{4})(\d{4})/, | |
'+$1 ($2) $3-$4', | |
], | |
[CODIGO_PAIS + DDD + DIGITO_OPCIONAL + NUMERO]: [ | |
/(\d{2})(\d{2})(\d{1})(\d{4})(\d{4})/, | |
'+$1 ($2) $3 $4-$5', | |
], | |
}; | |
const [regEx, matcher] = replacers[value.length]; | |
if (regEx && matcher) { | |
return value.replace(regEx, matcher); | |
} | |
return value; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment