3

In ExpressJS, how to right the following in one route using RegEx?

app.get('/blog', blog.list);
app.get('/blog/p/:page?', blog.list);

2 Answers 2

8

What the point of using RegExp here? Express patterns is simpler, yet almost as powerful as regular expressions:

app.get('/blog(?:/p/:page([0-9]+)?)?', blog.list);

This route will match all of the following urls:

  • /blog
  • /blog/
  • /blog/p
  • /blog/p/
  • /blog/p/123

In blog.list controller req.params.page will contain page number or will be undefined if it wasn't supplied.

Sign up to request clarification or add additional context in comments.

Comments

0

It seems like there might be compelling reasons to make these separate routes, but I'm not sure what you are doing with your app.

app.get(/^\/blog(?:\/p\/([0-9]+)?)?/, blog.list);

req.params[0] should be "20" at the route /blog/p/20, with req.params as null for /blog/p/ or /blog/ but with with both as functional routes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.