Match the current route with element in array

Viewed 282

I have multiple routes in an array like:

  • /app/manual/:id
  • /app/manuals/:id
  • /app/feedback
  • ...

In my react.js application I now want to match the location.pathname with the according path in my array and then I want to get the title of the array.

routes.find(x => x.path === location.pathname)?.title;

The problem is that with my solution only paths without any parameters get matched. So /app/manual/manual4 would not get matched while /app/feedback would get matched

I tried doing it with regex, but without any success.

routes.find(x => location.pathname.match(new RegExp(".*" + x.path+ "/.*")))?.title
1 Answers

If the path contains /:id you can location.pathname.replace(/\/[^\/]+$/, '/:id') so that you can compare .../:id to .../:id. Example using hard-coded pathname instead of location.pathname:

const routes = [
  { path: '/app/manual/:id', title: 'Manual' },
  { path: '/app/feedback', title: 'Feedback' },
  { path: '/questions/66829042/:id', title: 'Bingo!' }
];
const pathname = '/questions/66829042/match-the-current-route-with-element-in-array';
let title = routes.find(x => x.path.match(/:id$/) ?
  x.path === pathname.replace(/\/[^\/]+$/, '/:id') :
  x.path === pathname)?.title;
console.log('pathname: ' + pathname);
console.log('title: ' + title);

Result:

pathname: /questions/66829042/match-the-current-route-with-element-in-array
title: Bingo!
Related