Skip to content

Instantly share code, notes, and snippets.

@codermarcos
Created July 5, 2020 07:49
Show Gist options
  • Save codermarcos/b906be971de82cd4e1c4799abe0f781a to your computer and use it in GitHub Desktop.
Save codermarcos/b906be971de82cd4e1c4799abe0f781a to your computer and use it in GitHub Desktop.
A simple mask with a regexp javascript
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