How to add Cardboard Mask?

7

I have 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 a ('space') to every 4 digits. I'd like to add a period instead of space.

What should I change?

    
asked by anonymous 25.11.2016 / 16:46

2 answers

2

The code below:

  • Allows only digits;

  • Place one dot every 4 characters;

  • Remove the dot if it is left over;

  • Size limits;

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"))
    
25.11.2016 / 17:07
4

You do not need to have so many conditions for different scenarios.

You can simplify and do 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% w / w, the regex will look for groups from 1 to 4 and \d{1,4}/g joins these pieces with .join('.'); .

    
25.11.2016 / 17:06