How to use a regex for route matching in Express and Node.js?

Sometimes, we want to use a regex for route matching in Express and Node.js

In this article, we’ll look at how to use a regex for route matching in Express and Node.js.

How to use a regex for route matching in Express and Node.js?

To use a regex for route matching in Express and Node.js, we can use a regular JavaScript regex as route path argument.

For instance, we write

app.get(/^/(discussion|page)/(.+)/, (req, res, next) => {
  //...
});

to call app.get with a regex that matches discussion or page with any characters after either one.

Conclusion

To use a regex for route matching in Express and Node.js, we can use a regular JavaScript regex as route path argument.