JSFiddle - React, Tailwind, and code Playground
HTML
<input type="text" name="ao_cpf" id="ao_cpf" placeholder="CPF" maxlength="14" onMouseOut="formatar('###.###.###-##', this)" onKeyUp="formatar('###.###.###-##', this)" />
JavaScript
function formatar(mascara, documento){
var i = documento.value.length;
if(i < 14){
var saida = mascara.substring(0,1);
var texto = mascara.substring(i);
if (texto.substring(0,1) != saida){
documento.value += texto.substring(0,1);
}
if(i >= 11){
var ao_cpf=document.getElementById("ao_cpf").value;
ao_cpf = ao_cpf.replace( /\D/g , "");
ao_cpf = ao_cpf.replace( /(\d{3})(\d)/ , "$1.$2");
ao_cpf = ao_cpf.replace( /(\d{3})(\d)/ , "$1.$2");
ao_cpf = ao_cpf.replace( /(\d{3})(\d{1,2})$/ , "$1-$2");
document.getElementById("ao_cpf").value = ao_cpf;
}
}
}