JSFiddle - React, Tailwind, and code Playground
by Rui Leite
HTML
<input id="txtRg" type="text" value="12345678-9" />
<input type="button" value="Formatar" onclick="imprimeFormatado()" />
<div id="divResultado"></div>
JavaScript
function Rg(v){
v=v.replace(/\D/g,"");
if(v.length == 9) v=v.replace(/(\d{2})(\d{3})(\d{3})(\d{1})$/,"$1.$2.$3-$4");
else throw "Número de dígitos insuficiente ou excessivo no RG " + v;
return v;
}
function imprimeFormatado(){
try {
document.getElementById("divResultado").innerHTML = Rg(document.getElementById("txtRg").value);
} catch(e) {
document.getElementById("divResultado").innerHTML = "Número insuficiente ou excessivo de caracteres. Por favor, altere o RG e tente novamente.";
}
}