How to add Card Mask?

Asked

Viewed 3,172 times

7

I’m having a problem to re-adapt this function in JS.

function mcc(v){
v=v.replace(/\D/g,"");
v=v.replace(/^(\d{4})(\d)/g,"$1 $2");
v=v.replace(/^(\d{4})\s(\d{4})(\d)/g,"$1 $2 $3");
v=v.replace(/^(\d{4})\s(\d{4})\s(\d{4})(\d)/g,"$1 $2 $3 $4");
return v;
}

Basically it adds one('space') to every 4 digits. I would like to add one dot instead of space.

What should I change?

  • The code for point is \. (backslash + stitch). Just replace.

  • I don’t get it, I could add the code he posted the most to your change?

  • @Cleition, I tried to do this, but it’s not right!

  • Not yet -> 1234.12345678912345 , not so -> 123.5678.9123.1234

  • I only considered replacing space by point, not corrections in the code. This was not requested.

2 answers

3

You don’t need to be in so much condition for different scenarios.

You can keep it simple and do it like this:

function mcc(v) {
    v = v.replace(/\D/g, "");
    return v.match(/\d{1,4}/g).join('.');
}

const testes = ['3 3 3', '333333333333', '33333'];
console.log(JSON.stringify(testes.map(mcc)));

Using \d{1,4}/g regex will search groups from 1 to 4 and the .join('.'); joins these pieces with ..

  • Thanks @Sergio, your answer also solved my problem! D

1


The code below:

  • Allows only digits;

  • Put a dot every 4 characters;

  • Remove the point if left over;

  • Limits the size;

function mcc(v){
  v = v.replace(/\D/g,""); // Permite apenas dígitos
  v = v.replace(/(\d{4})/g, "$1."); // Coloca um ponto a cada 4 caracteres
  v = v.replace(/\.$/, ""); // Remove o ponto se estiver sobrando
  v = v.substring(0, 19)// Limita o tamanho

  return v;
}

console.log(mcc("12341234123412341"))

  • Thanks @Sorack solved my problem!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.