Create character pattern as in a CPF - Javascript

0

What I want to do is: type a CPF without points or dash and then add the dots and dash with JS, create a pattern. Example: I write 99999999999 and the system returns me 999.999.999-99. How do I do this in pure Javascript?

    
asked by anonymous 17.02.2018 / 21:21

2 answers

4

You can use Regular Expressions . Ex:

^([\d]{3})([\d]{3})([\d]{3})([\d]{2})$
 └───┬───┘└───┬───┘└───┬───┘└───┬───┘
     │        │        │        └───── Captura os dois últimos dígitos
     │        │        └────────────── Captura os valores entre 7º e 9º dígitos
     │        └─────────────────────── Captura os valores entre o 4º e 6º dígito
     └──────────────────────────────── Captura o três primeiros dígitos

Then just use: $1 , $2 , $3 and $4 to capture the groups.

Here's an example:

const cpf = document.querySelector("#cpf");

cpf.addEventListener("blur", () => {
  let value = cpf.value.replace(/^([\d]{3})([\d]{3})([\d]{3})([\d]{2})$/, "$1.$2.$3-$4");
  
  cpf.value = value;
});
<input type="text" value="" id="cpf" />

You can also use the keyup event to do this as you type the text.

const cpf = document.querySelector("#cpf");

cpf.addEventListener("keyup", () => {
  let value = cpf.value.replace(/[^0-9]/g, "").replace(/^([\d]{3})([\d]{3})?([\d]{3})?([\d]{2})?/, "$1.$2.$3-$4");
  
  cpf.value = value;
});
<input type="text" value="" id="cpf" />
    
17.02.2018 / 21:31
0

Another way using regex:

var cpf = document.querySelector("#cpf");

cpf.addEventListener("blur", function(){
   cpf.value = cpf.value.match(/.{1,3}/g).join(".").replace(/\.(?=[^.]*$)/,"-");
});
<input type="text" id="cpf" maxlength="11" />

The regex /.{1,3}/g breaks the 3-by-3 character string creating an array. join(".") reads to array by inserting a point between each item, and replace with regex /\.(?=[^.]*$)/ replaces the last point " . " with hyphen " - ".

    
19.02.2018 / 01:29