Zainab Hussain
Zainab Hussain

Reputation: 333

Replace matched regex group by occurence

I'm working on a drag and drop function for SVG path, which lets a user move the co-ordinates of the path.

Please consider the string below:

M162.323 150.513L232.645 8L303.504 149.837L461.168 173.5L347.156 284.5L373.605 440.728L233.5 367.854L91.7415 442L118.424 284.883L5.151 173.549Z

Would it be possible to replace a specific(let's say the 4th) occurence of a matched regex group using the .replace method?

Regex:

[A-Z](-?\d*\.?\d*\s-?\d*\.?\d*)

Upvotes: 2

Views: 49

Answers (2)

Felix G
Felix G

Reputation: 861

regex.exec() is a method that is used to find the next match in a string based on a regular expression. It returns an array containing the matched string and any capturing groups, or null if no match is found. This method can be used in a loop to iterate over all matches in a string and adjust the match accordingly.

let string = "M162.323 150.513L232.645 8L303.504 149.837L461.168 173.5L347.156 284.5L373.605 440.728L233.5 367.854L91.7415 442L118.424 284.883L5.151 173.549Z";
let regex = /[A-Z](-?\d*\.?\d*\s-?\d*\.?\d*)/g;

// Replace the 4th match
let newString = "";
let index = 0;
let match;

while (match = regex.exec(string)) {
  if (index === 3) {
    // Do something to modify the 4th match
    newString += match[0].replace(/-?\d*\.?\d*\s-?\d*\.?\d*/, "REPLACED");
  } else {
    // Leave other matches unchanged
    newString += match[0];
  }
  index++;
}

console.log(newString);

Upvotes: 2

Andrew Parks
Andrew Parks

Reputation: 8107

const s = 'M162.323 150.513L232.645 8L303.504 149.837L461.168 173.5L347.156 284.5L373.605 440.728L233.5 367.854L91.7415 442L118.424 284.883L5.151 173.549Z'

let n = 4, regex = /[A-Z](-?\d*\.?\d*\s-?\d*\.?\d*)/gm
console.log(s.replace(regex, m => --n ? m : 'hello'))

Upvotes: 2

Related Questions