Skip to content

Instantly share code, notes, and snippets.

@phsantiago
Created August 22, 2017 15:19
Show Gist options
  • Save phsantiago/9ffd8f130649b970774f745ca6f7a3ae to your computer and use it in GitHub Desktop.
Save phsantiago/9ffd8f130649b970774f745ca6f7a3ae to your computer and use it in GitHub Desktop.
Máscara para CPF e CNPJ em javascript utilizando ES6
const mask = (v) => {
v=v.replace(/\D/g,"")
let len = v.length
if (len < 12) {
v=v.replace(/(\d{3})(\d)/,"$1.$2")
.replace(/(\d{3})(\d)/,"$1.$2")
.replace(/(\d{3})(\d{1,2})$/,"$1-$2")
} else {
v=v.replace(/^(\d{2})(\d)/,"$1.$2")
.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3")
.replace(/\.(\d{3})(\d)/,".$1/$2")
.replace(/(\d{4})(\d)/,"$1-$2")
}
return v.substring(0,18)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment