I cut my teeth on Perl. I'm pretty comfortable with regular expressions (but still prone to errors).
Why does (*)
work as a regular expression in an Express route named param?
Why doesn't (.*)
work as a regular expression in an Express route named param?
Is something like ([\\w:./]+)
a more reliable way to do it?
I'm trying to use a route parameter that is intended to have slashes in the value.
e.g.
If the request is:
http://www.example.com/new/https://www.youtube.com/trending
... and I'm using this route:
app.get('/new/:url', (req, res) => {
console.log('new')
console.log(req.params.url)
})
I want url
to equal https://www.youtube.com/trending
I understand that the path is split on the slashes, so I thought I could use a regular expression in parentheses after the named parameter to also match the slashes.
I tried /new/:url(.*)
, which I thought should greedily match anything, including the slashes, but this made the route fail completely. Why doesn't this work?
Through my own trial and error, I found that /new/:url([\\w:./]+)
works. This makes sense to me, but seems unnecessarily complex. Is this "the right way"?
The one that perplexes me the most is one I found in a YouTube video example... Why does /new/:url(*)
work? The *
says 0 or more of the previous item, but there's nothing before the asterisk.
I have a feeling that the answer lies in this GitHub issue, but it's not clear to me from reading the thread exactly what's happening. Does (*)
rely on a bug that's likely to be corrected in the next release of Express?