1

How can I replace just last matching result with regex?

Example:

path = /:demo/:demo1/:demo2
path.replace(new RegExp('/:[^/]+'), '/(?<pathinfo>[^/]+)')

How can I always replace just last one?

Output should be:

/:demo/:demo1/(?<pathinfo>[^/]+)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
mbrc
  • 3,523
  • 13
  • 40
  • 64
  • Does this answer your question? [JavaScript: replace last occurrence of text in a string](https://stackoverflow.com/questions/2729666/javascript-replace-last-occurrence-of-text-in-a-string) – Ryan Wilson Feb 23 '23 at 21:32
  • 1
    Honestly you could also just split it by `/:`, add all the first parts together and replace the last one. (instead of using fancy regex/pinning it to the end) – Yarin_007 Feb 23 '23 at 21:33
  • 1
    There's rarely a good reason to use `new RegExp()` with a fixed regexp, use a regexp literal. – Barmar Feb 23 '23 at 21:33
  • 1
    The simple answer is to add a `$` anchor to the end of your regexp. – Barmar Feb 23 '23 at 21:34
  • 1
    If anchoring the regex using `$` is not an option and you have the freedom to change the regex and replacement. Using the regex `(.*)/:[^/]+` with replacement to `$1(?[^/]+)` is probably the easiest. So `path.replace(/(.*)\/:[^\/]+/, '$1(?[^/]+)')` – 3limin4t0r Feb 23 '23 at 22:44

1 Answers1

1

Please try below solution this should solve your problem:

function replaceLastMatch(path, regex, replacement) {
  const matches = path.match(regex);
  if (matches && matches.length > 0) {
    const lastMatch = matches[matches.length - 1];
    const lastIndex = path.lastIndexOf(lastMatch);
    return path.substring(0, lastIndex) + path.substring(lastIndex).replace(lastMatch, replacement);
  }
  return path;
}

const path = '/:demo/:demo1/:demo2';
const regex = /\/:[^/]+(?=\/|$)/g;
const replacement = '/(?<pathinfo>[^/]+)';
const result = replaceLastMatch(path, regex, replacement);
console.log(result); // Output: /:demo/:demo1/(?<pathinfo>[^/]+)

rafalkasa
  • 1,743
  • 20
  • 20