Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for route matching in Express

I'm not very good with regular expressions, so I want to make sure I'm doing this correctly. Let's say I have two very similar routes, /discussion/:slug/ and /page/:slug/. I want to create a route that matches both these pages.

app.get('/[discussion|page]/:slug', function(req, res, next) {   ...enter code here... }) 

Is this the correct way to do it? Right now I'm just creating two separate routes.

someFunction = function(req, res, next) {..} app.get('/discussion/:slug', someFunction) app.get('/page/:slug', someFunction) 
like image 467
Jonathan Ong Avatar asked Jun 01 '12 22:06

Jonathan Ong


People also ask

What is Express Router ()?

The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests.

How can we create Chainable route handlers for a route path in Expressjs app?

Answer: A is the correct option. By using app. route() method, we can create chainable route handlers for a route path in Express.


2 Answers

app.get('/:type(discussion|page)/:id', ...) works

like image 112
Jonathan Ong Avatar answered Sep 28 '22 12:09

Jonathan Ong


You should use a literal javascript regular expression object, not a string, and @sarnold is correct that you want parens for alternation. Square brackets are for character classes.

const express = require("express"); const app = express.createServer(); app.get(/^\/(discussion|page)\/(.+)/, function (req, res, next) {   res.write(req.params[0]); //This has "discussion" or "page"   res.write(req.params[1]); //This has the slug   res.end(); });  app.listen(9060); 

The (.+) means a slug of at least 1 character must be present or this route will not match. Use (.*) if you want it to match an empty slug as well.

like image 39
Peter Lyons Avatar answered Sep 28 '22 11:09

Peter Lyons