0

I am trying to write a function that checks if a route is included in an array of routes:

const routes = ['/test', '/documentation/*']

function checkRoute(route) {
  if (routes.includes(route)) {
    console.log('Included!!')
  } else { 
    console.log('Not included!')
  }
}

The part I need help with is how to handle the wildcard * - basically, I want any route that has the /docs/ prefix to be included such as:

/documentation/docs.json, /documentation/index.html

Besides doing some very messy string manipulation, I am not sure how to achieve this. Any help would be greatly appreciated!

John Grayson
  • 1,378
  • 3
  • 17
  • 30

2 Answers2

2

You can use regex.

const routes = ['\\/test\\/*', '\\/documentation\\/*']

function checkRoute(route) {
  let regex = new RegExp(route);
  let matchedRoutes = routes.filter(route => regex.test(route))
}
rishabh0211
  • 433
  • 4
  • 10
  • John should change `'/documentation/*'` to `'/documentation/.*'` since it's regex, not wildcard matching. Or perhaps `'^/documentation/.*'` so it only matches from the root of the route. – Chris Jun 30 '20 at 18:07
  • @Chris `.*` isn't needed at the end, unless you anchor it with `$`. – Barmar Jun 30 '20 at 18:15
  • @Chris I guess it should be changed to `\\/documentation\\/*` for the regex to be properly created with RegExp. `new RegExp('\\/documentation\\/*')` returns `/\/documentation\/*/` – rishabh0211 Jun 30 '20 at 18:17
  • Thanks! But is there a way to do this that uses my original `routes` array `const routes = ['/test', '/documentation/*']` ? – John Grayson Jun 30 '20 at 19:11
0

Here is a simple form of wildcard match function. It is not a bad idea to use it and support all types of wildcard comparrsion:

https://stackoverflow.com/a/32402438/635891

Mostafa Barmshory
  • 1,849
  • 24
  • 39