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>[^/]+)
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>[^/]+)
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>[^/]+)