2

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?

1 Answer 1

2

You can use capturing group and replace by first capturing group

.replace(/((?:[^,]*,){2}[^,]*),/g, "$1:");
          ^                  ^

The captured group will capture the matched string except the third comma which is $1 in the replacement string.

console.log('1,2,3,4,5,2,3,4,5,2,3,4,5'.replace(/((?:[^,]*,){2}[^,]*),/g, "$1:"));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.