in this example string '1,2,3,4,5' I am trying to capture and replace the 3rd occurence of the comma , character
this code here
'1,2,3,4,5'.match(/(?:[^,]*,){2}[^,]*(,)/)
matches 1,2,3 and the comma im looking for
but not sure how to replace just the comma
'1,2,3,4,5'.replace(/(?:[^,]*,){2}[^,]*(,)/, "$")
replaces everything before 4 giving $4,5
i just want a string result like 1,2,3$4,5 for example
I have achieved this task in two different ways, with array split and slice and with a String#replace that takes a callback
//splice
let parts = [];
let str = "1,2,3,4,5";
let formatted = ((parts = str.split(",")).slice(0,3)).join("-") + ' ' + parts.slice(3).join(":")
//callback
let str = "1,2,3,4,5";
str.replace(/,/g, (() => {
let count = 0;
return (match, position) => {
count += 1;
if(count == 3) return ' ';
else if(count < 3) return '-';
else return ':';
});
})())
Is this even possible with a plain String#replace?