Get array of all named group pattern in URLPattern

30 Views Asked by At

Given the following URLPattern:

new URLPattern('/path/example/:name/:age')

I am looking to return an array of all named groups. ['name', 'age']

I don't see a simple library / class to do this?

I need this to take into account all supported url paths for instance /users/:id/:tab(home|photos|bio).

One way to do this that does not satisfy /users/:id/:tab(home|photos|bio) is to feed the url back into itself like this:

const x = new URLPattern({ pathname: '/path/example/:name/:age' })
const r = x.exec('https://localhost:3000/path/example/:name/:age')
console.log(Object.keys(r.pathname.groups))
[ "name", "age" ]
1

There are 1 best solutions below

0
SaSkY On

Try this:

(?<=\/:)\w+/g

\w+ means search for one or more word character from a to z or from A to Z or from 0 to 9 or an underscore _, then (?<=\/:) it insures that the string is preceded by a /: but it does not include the value of /: as part of the result.

var x = "https://localhost:3000/path/example/:name/:age";

var arr = x.match(/(?<=\/:)\w+/g);

console.log(arr);