Home > Net >  Replace matched regex group by occurence
Replace matched regex group by occurence

Time:12-05

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*)

CodePudding user response:

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'))

CodePudding user response:

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);

  • Related