1

I would like a means to match as many URL parameters as possible example

/teams/:teamID/players/:playerID/seasons/:seasonID/detail

would match anything starting with /teams and match as many parameters present, up to /detail (and only up to)

/Giants => { teamID: null, playerID: null, seasonID: null }
/Giants/123 => { teamID: 123, playerID: null, seasonID: null }
/Giants/123/players/ => same as above
/Giants/123/players/456/seasons/2020/detail => { teamId: 123, playerID: 456, seasonID: 2020 }
/Giants/123/players/446/seasons/2020 => same as above

and not match

/Giants/123/players/456/seasons/2020/detail/12345

I'm using path-to-regexp.

Brad
  • 146,404
  • 44
  • 300
  • 476
blue18hutthutt
  • 2,961
  • 4
  • 29
  • 51
  • Are you using Express? Or, something else? – Brad Apr 21 '20 at 02:27
  • @Brad I'm in a React app and trying to use path-to-regexp (which Express uses to parse URL route patterns I believe) – blue18hutthutt Apr 21 '20 at 02:57
  • @blue18hutthutt In that case, I'd recommend dropping the Node.js tag and mentioning in your question the module. – Brad Apr 21 '20 at 03:00
  • Re-opened the question, as given the details in the comments, it's different than the duplicate it was closed as. – Brad Apr 21 '20 at 03:41

2 Answers2

0

If there is a possibility of not using regex, you can probably split the URL into an array using / as a separator. Get every element of the array that's after team all the way until the details.

Aviv Lo
  • 1,727
  • 1
  • 4
  • 15
0

I found a nice library that does exactly what I need, is extremely lite and uses well-tested pieces of Backbone.js to do the pattern matching:

https://github.com/HenrikJoreteg/feather-route-matcher

Examples:

pattern: '/users/:id' 
url: '/something-else' 
extracted params: nothing, because it won't match

pattern: '/users/:id' 
url: '/users/scrooge-mc-duck' 
extracted params: {id: 'scrooge-mc-duck'}

pattern: '/users/:id' 
url: '/users/47' 
extracted params: {id: '47'}

pattern: '/schools/:schoolId/teachers/:teacherId' 
url: '/schools/richland/teachers/47' 
extracted params: {schoolId: 'richland', teacherId: '47'}

This provided me exactly what I wanted and needed

blue18hutthutt
  • 2,961
  • 4
  • 29
  • 51