How to get padStart to properly handle regular grouping flags such as $1?

in the following code, I want to complete the number after "p" to 3 digits, but I find that no matter how many bits are after p, there is always a 0 in front of it.

var a="18917304_p1234";
a.replace(/(\d.*p)(\d.*)/,"$1"+("$2".padStart(3, "0")));
// "18917304_p01234"

after my random analysis, it may be because padStart does not get the value of $2 , but treats $2 as a normal string. The word $2 is 2 in length, so padStart always makes up a zero.

later, it was solved by a different way of writing, but if you don"t rewrite it, is there a more direct way to deal with this situation?

a.replace(/(\d.*p)(\d.*)/,function (...str) {
    return str[1]+str[2].padStart(3, "0");
});

your guess is correct. It's just a question of the basic syntax of js and has nothing to do with replace : when padStart is executed, replace has not been executed, and $2 is not a variable

.

so a.replace (/ (\ d.roomp) (\ d.*) /,'$1percent + ('$2'.padStart (3,'0'))

is actually a.replace (/ (\ d.roomp) (\ d.q.) /,'$1' +'0 $2')

of course, if you want to get the variable of $1 recording 2, you can capture it by executing the rule, but it is not as concise as the answer you will add later, such as:

var reg = /(\d.*p)(\d.*)/;
reg.exec('18917304_p1234');
var str = RegExp.$1 + RegExp.$2.padStart(3, '0');
Menu