How to write right regular expression for my Route path in React JS

Viewed 241

I have some troubles with writing regular expressions in my React JS application. Suppose that my have to check only paths like "/articles/page-2" or "/articles/page-1" or just "/articles/". What is the right way for doing it correctly?

<Route path={'/articles/(page-)?:pageNumber?'}/>

I've tried following path, but it's not the right path. This route would render it even when URL is "/articles/-3"

2 Answers

For capturing only pageNumber is better to break into 2 routes. Create the first for capturing /articles only and the second with the desired pattern.

you can write as page-:pageNumber(\d), where \d means digit. you must also include exact={true}, to ensure an exact match for your path. With that you can use useParams later to extract pageNumber:

<Route path={'/articles'} exact={true} />
<Route path={'/articles/page-:pageNumber(\d)'} exact={true} />

Not sure if I understood, and also not sure if you can do that.. but try

<Route path={`/articles/${pageNumber ? "page-" + pageNumber : ''}`}/>
Related