Skip to content

Instantly share code, notes, and snippets.

@garbinmarcelo
Forked from davidalves1/formatar_cnpj_cpf.md
Created January 30, 2020 13:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save garbinmarcelo/ef28fa0743da9d56a7194f875b897cfb to your computer and use it in GitHub Desktop.
Save garbinmarcelo/ef28fa0743da9d56a7194f875b897cfb to your computer and use it in GitHub Desktop.
Função para formatar CNPJ e CPF, disponível em PHP e JS

PHP

function formatCnpjCpf($value)
{
  $cnpj_cpf = preg_replace("/\D/", '', $value);
  
  if (strlen($cnpj_cpf) === 11) {
    return preg_replace("/(\d{3})(\d{3})(\d{3})(\d{2})/", "\$1.\$2.\$3-\$4", $cnpj_cpf);
  } 
  
  return preg_replace("/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/", "\$1.\$2.\$3/\$4-\$5", $cnpj_cpf);
}

JS

function formatCnpjCpf(value)
{
  const cnpjCpf = value.replace(/\D/g, '');
  
  if (cnpjCpf.length === 11) {
    return cnpjCpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/g, "\$1.\$2.\$3-\$4");
  } 
  
  return cnpjCpf.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/g, "\$1.\$2.\$3/\$4-\$5");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment