4
I am running a replace with regular expressions to format a string, such as CPF:
var cpf = '99999999999';
cpfFormatado = cpf.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$+');
console.log(cpfFormatado); // 999.999.999-99
I am trying to reduce the regular expression, however I am not able to find the correct way to use the groups in the substitution string:
var cpf = '99999999999';
cpfFormatado = cpf.replace(/(\d{3}){3}(\d{2})/, '$1.$2.$3-$+');
console.log(cpfFormatado); // 999.99.$3-99
How could I get the same result from the first code using the regular expression of the second?
that’s what you’re looking for?
(\d{3})(\1)(\1)(\d{2})
– Guilherme Lautert
Your first exit is wrong, the last group is $4.
– Luis Henrique
@Luishenrique is not wrong.
$+
picks up the last found group, ie will return the group(\d{2})
. Utilise$4
would give the same result.– Oeslei
@Guilhermelautert His expression worked perfectly. He could write a reply explaining how it works?
– Oeslei
Strange that I circled here on the console and it didn’t work.
– Luis Henrique