Jack Guy
Jack Guy

Reputation: 8523

RegEx help- Express routing url

I've read from other Stack Overflow posts that you can use regular expressions to route various URLs. I've never really used RegExps before, so I need some help. How would I route all URLs that begin with /lobby/ followed by ten digits? Like so

app.get("/lobby/0000000000", function (req, res) ...

Thanks.

Upvotes: 3

Views: 11632

Answers (2)

enducat
enducat

Reputation: 1706

app.get('/lobby/:id', function(req, res){
    console.log( req.params.id );
    res.end();
});

or

app.get('/lobby/((\\d+))', function(req, res){
    console.log( req.params[0] );
    res.end();
});

or if the URL needs to be exactly 10 digits:

app.get('/lobby/((\\d+){10})', function(req, res){
    console.log( req.params[0] );
    res.end();
});

Upvotes: 5

hexacyanide
hexacyanide

Reputation: 91669

Here's a working example:

app.get(/^\/lobby\/[0-9]{10}$/, function(req, res) {
  // route handler here
});

Alternatively, you can use parameter checking:

app.param(function(name, fn){
  if (fn instanceof RegExp) {
    return function(req, res, next, val){
      var captures;
      if (captures = fn.exec(String(val))) {
        req.params[name] = captures;
        next();
      } else {
        next('route');
      }
    }
  }
});

app.param('id', /^[0-9]{10}$/);
app.get('/lobby/:id', function(req, res){
  res.send('user ' + req.params.id);
});

Upvotes: 10

Related Questions