英文:
Replace just last matching result with regex
问题
如何只用正则表达式替换最后一个匹配结果?
示例:
path = /:demo/:demo1/:demo2
path.replace(new RegExp('/:[^/]+'), '/(?<pathinfo>[^/]+)')
如何始终只替换最后一个?
输出应该是:
/: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>[^/]+)
答案1
得分: 1
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); // 输出: /: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>[^/]+)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论