Skip to content

Instantly share code, notes, and snippets.

@henriquemenezes
Last active August 26, 2021 15:18
Show Gist options
  • Save henriquemenezes/9ecf2124fd76a2ed6f7e to your computer and use it in GitHub Desktop.
Save henriquemenezes/9ecf2124fd76a2ed6f7e to your computer and use it in GitHub Desktop.

Javascript

function cpfMask(cleanValue) {
  return cleanValue.replace(/^(\d{3})(\d{3})(\d{3})(\d{2}).*/, '$1.$2.$3-$4');
}

function cnpjMask(cleanValue) {
  return cleanValue.replace(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2}).*/, '$1.$2.$3/$4-$5');
}

Ruby

def cpf_mask(clean_value)
  clean_value.sub(/^?(\d{3})?(\d{3})?(\d{3})?(\d{2}).*/, "\\1.\\2.\\3-\\4")
end

def cnpj_mask(clean_value)
  clean_value.sub(/^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2}).*/, "\\1.\\2.\\3/\\4-\\5")
end

Python

def cpf_mask(clean_value):
    return re.sub('(\d{3})(\d{3})(\d{3})(\d{2})', '\\1.\\2.\\3-\\4', clean_value)

def cnpj_mask(clean_value):
    return re.sub('(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})', '\\1.\\2.\\3/\\4-\\5', clean_value)

Java

cpf.replaceAll("(\\d{3})(\\d{3})(\\d{3})(\\d{2})", "$1.$2.$3-$4")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment