Created
July 5, 2020 07:49
-
-
Save codermarcos/b906be971de82cd4e1c4799abe0f781a to your computer and use it in GitHub Desktop.
A simple mask with a regexp javascript
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
const cnpj = [/\D/, /\D/, '.', /\D/, /\D/, /\D/, '.', /\D/, /\D/, /\D/, '/', /\D/, /\D/, /\D/, /\D/, '-', /\D/, /\D/]; | |
const celphone = ['+', '5', '5', ' ', /\D/, /\D/, ' ', /\D/, ' ', /\D/, /\D/, /\D/, /\D/, /\D/, /\D/, /\D/, /\D/]; | |
const cpf = [/\D/, /\D/, /\D/, '.', /\D/, /\D/, /\D/, '.', /\D/, /\D/, /\D/, '.', /\D/, /\D/]; | |
const cep = [/\D/, /\D/, /\D/, /\D/, /\D/, '-', /\D/, /\D/, /\D/]; | |
function mask(e, formater) { | |
const result = []; | |
const { target } = e; | |
for (let i = 0; i < target.value.length; i++) { | |
if (i >= formater.length) break; | |
result[i] = typeof formater[i] !== 'string' | |
? target.value[i].replace(formater[i], '') | |
: formater[i]; | |
} | |
e.target.value = result.join(''); | |
} | |
input.addEventListener('input', (e) => mask(e, cnpj)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment