How to match an optional segment in vue-router with path-to-regexp

554 views Asked by At

Vue-Router uses https://github.com/pillarjs/path-to-regexp to convert paths to regular expressions.

I have been trying to create an expression that matches an optional segment within an path but without success.

I have been using http://forbeslindesay.github.io/express-route-tester/ with package version 0.1.7 for testing.

The path should look like this:

/:required parameter/(identifier/:parameter1/:parameter2)?/* The first parameter should always be required. if the first parameter matches the word "identifier" as second part of the expression then parameter1 and parameter2 are required two. If not then none of the two parameters can be used and * should be matched.

What I have tried:

/:required/(identifier/:optional1/:optional2)?/* The route

/required/identifier/optional1/optional2/bla should be qual to

/required/bla

1

There are 1 answers

0
Emma On

My guess is that you're trying to write some expression, that'd look like:

(/required/)(?:identifier/optional1/optional2/)(.*)

and replace it with $1$2.


If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.