Skip to content

Instantly share code, notes, and snippets.

@johnatandias
Created July 17, 2020 16:06
Show Gist options
  • Save johnatandias/c89bd089058e6e18c03906aeebbde1bf to your computer and use it in GitHub Desktop.
Save johnatandias/c89bd089058e6e18c03906aeebbde1bf to your computer and use it in GitHub Desktop.
Format CPF and CPNJ
const formatCPF = cpf => {
const invalidCPF = !cpf || cpf.length !== 11;
if (invalidCPF) return cpf;
return cpf
.replace(/[^\d]/g, '')
.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
};
const formatCNPJ = cnpj => {
const invalidCNPJ = !cnpj || cnpj.length !== 14;
if (invalidCNPJ) return cnpj;
return cnpj
.replace(/[^\d]/g, '')
.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment