dimanche 1 mars 2015

Regex keeps trailing slash in capture group


So, I've tried making a little Regex expression to fetch the requested URL, minus the starting an trailing slash.


One little catch, the trailing slash wont always be there, for instance if the user requests "/test/example/", they can also request "/test/example". So I tried to make a method to handle that:



req.url.match(/^(?:\/)(.+)(?:[\/])?$/i)[1]


Although, if I request a path like "/test/example/", it keeps the trailing slash, and returns "test/example/" in the capture group...? Basically what I wanted to avoid. (So, all it's doing is removing the starting slash)


Now, I tried removing the ? that's next to the $ symbol. But this just causes an error when requesting "/test/example" (something without the trailing slash), because [1] would be null.


I made an example on regex101, which you can view here. As you can see, the capture group includes the ending slash, even though in my expression, I thought I told it to not do that.


TL;DR: Regex is still capturing trailing slash, even though I don't want to do (and keep in mind that the trailing slash wont always be present).





Aucun commentaire:

Enregistrer un commentaire