replace using regular expressions

3

I'm running a regular replace tag to format a string, such as the 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'm trying to reduce the regular expression, however I can not find the correct way to use the groups in the replacement 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 to the same result as the first code using the second regular expression?

    
asked by anonymous 26.03.2015 / 19:43

2 answers

3

Can not do this. When you reduce (\d{3})(\d{3})(\d{3}) to this (\d{3}){3} , you are deleting two capture groups, with the first capture group being overwritten twice, causing it to get the value of the last capture.

var cpf = '12345678901';
cpfFormatado = cpf.replace(/(\d{3}){3}(\d{2})/, '$1.$2.$3-$+');
console.log(cpfFormatado); // 789.01.$3-$+

To know what is available to use, just use a replacement function, and see what it receives as arguments:

var cpf = '12345678901';
cpfFormatado = cpf.replace(/(\d{3}){3}(\d{2})/, function() {
    debugger; // ao parar aqui vamos ver o que tem dentro de arguments
    console.log(JSON.stringify(arguments));
});

The arguments passed to the function in the above example are:

["12345678901", "789", "01", 0, "12345678901"]

See how "789" appears in group 1.

    
26.03.2015 / 19:54
0

As requested:

(\d{3})()()(\d{2})

Composition

(\d{3})   -  grupo nº 1
()      -  grupo nº 2, que utiliza a mesma expressão do grupo 1
()      -  grupo nº 3, que utiliza a mesma expressão do grupo 1
(\d{2})   -  grupo nº 4

Explanation

You can make use of expressions already made, making them a group and calling the shortcuts - , remembering that you can only have a maximum of 9 shortcuts .

At a Glance (\d{3}) is the grouped expression that has the

    
26.03.2015 / 20:03