Created
July 15, 2019 17:23
-
-
Save jrrio/b2f80695c2cc076ca4727fb32e94a447 to your computer and use it in GitHub Desktop.
Formatting mask for Brazilian CPF, CNPJ and CEP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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