【问题标题】:Match as many URL route parameters as possible with path-to-regexp?使用 path-to-regexp 匹配尽可能多的 URL 路由参数?
【发布时间】:2020-08-03 16:20:28
【问题描述】:

我想要一种方法来匹配尽可能多的 URL 参数示例

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

将匹配以 /teams 开头的任何内容,并匹配存在的尽可能多的参数,直到 /detail(并且最多)

/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

不匹配

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

我正在使用path-to-regexp

【问题讨论】:

  • 您使用的是 Express 吗?或者,别的什么?
  • @Brad 我在一个 React 应用程序中并尝试使用 path-to-regexp(我相信 Express 用来解析 URL 路由模式)
  • @blue18hutthutt 在这种情况下,我建议删除 Node.js 标记并在您的问题中提及模块。
  • 重新打开问题,因为在 cmets 中给出了详细信息,它与关闭时的副本不同。

标签: javascript regex url match


【解决方案1】:

我找到了一个很好的库,它完全符合我的需要,非常精简,并且使用经过良好测试的 Backbone.js 片段来进行模式匹配:

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

例子:

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'}

这正是我想要和需要的东西

【讨论】:

    【解决方案2】:

    如果有可能不使用正则表达式,您可以使用/ 作为分隔符将 URL 拆分为一个数组。获取数组中team 之后一直到details 的每个元素。

    【讨论】:

    • 我投反对票不是一个可行的答案吗?
    猜你喜欢
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    相关资源
    最近更新 更多