pillarjs / path-to-regexp

Turn a path string such as `/user/:name` into a regular expression

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Non captured element inside parameter

tbekaert opened this issue · comments

Hi guys and thanks for this lib !

I'm trying to retrieve params inside a path of mine but excluding some content from a specific param.

Basically, I'm trying to execute the equivalent of this regex /(?:\/(?<suffix>en|fr))?\/magazine(?:\/p-(?<page>[\d]+))?/ but with a path.

I've tried with the following code but I don't really like the fact that we have a named parameter (prefix) included in the response

const { match } = require('path-to-regexp')

const route = match(`/:suffix(en|fr)?/magazine/{:preffix(p-)}:page([\\d]+)`)

console.log(
  route('/fr/magazine/p-2')
)
// {index: 0, params: Object {page: "2", preffix: "p-", suffix: "fr"}, path: "/fr/magazine/p-2"}

Here is an example for you to test: https://runkit.com/tbekaert/non-captured-element-inside-parameter

Do you have any idea on how to achieve that?

Thanks a lot !

I updated your example here: https://runkit.com/blakeembrey/60064600d4cffa001a35e4da. Sharing this was very helpful, thank you 🙏

The solution to your issue is by moving the /p- into the "matching group" by wrapping with {}. So you'd end up with /:suffix(en|fr)?/magazine{/p-:page([\\d]+)}?.

Thanks a lot @blakeembrey !

That works like a charm