简体   繁体   中英

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 4 th ) occurence of a matched regex group using the .replace method?

Regex :

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

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 = /[AZ](-?\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);

 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 = /[AZ](-?\d*\.?\d*\s-?\d*\.?\d*)/gm console.log(s.replace(regex, m => --n? m: 'hello'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM