Skip to content

Instantly share code, notes, and snippets.

@jrrio
Created July 15, 2019 17:23
Show Gist options
  • Save jrrio/b2f80695c2cc076ca4727fb32e94a447 to your computer and use it in GitHub Desktop.
Save jrrio/b2f80695c2cc076ca4727fb32e94a447 to your computer and use it in GitHub Desktop.
Formatting mask for Brazilian CPF, CNPJ and CEP
/**
* @param {String} str - a string to be formatted.
* @param {String} msk - 'CNPJ', 'CPF' or 'CEP' used in Brazil.
*/
function formatMask(str, msk) {
var a = str.replace(/[^\d]+/g, ''); // remove non digit chars.
switch (msk) {
case "CNPJ":
a = a.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5');
break;
case "CPF":
a = a.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
break;
case "CEP":
a = a.replace(/(\d{5})(\d{3})/, '$1-$2');
break;
default:
break;
}
return a;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment