Skip to content

Instantly share code, notes, and snippets.

@fatecitu
Last active May 24, 2023 01:10
Show Gist options
  • Save fatecitu/c042575baf416947aa2b9306f17add82 to your computer and use it in GitHub Desktop.
Save fatecitu/c042575baf416947aa2b9306f17add82 to your computer and use it in GitHub Desktop.
Formatar RG com JS
function formatarRG(campo) {
// Remove caracteres não numéricos
var rg = campo.value.replace(/\D/g, '');
// Adiciona pontos e traço conforme o usuário digita
rg = rg.replace(/(\d{2})(\d)/, '$1.$2');
rg = rg.replace(/(\d{3})(\d)/, '$1.$2');
rg = rg.replace(/(\d{3})(\d{1,2})$/, '$1-$2');
// Verifica se o último dígito é X e adiciona a string de retorno
if (campo.value.charAt(campo.value.length - 1).toUpperCase() === 'X') {
rg += '-X';
}
// Atualiza o valor do campo
campo.value = rg;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment