RegEx help- Express routing url

10,228

Solution 1

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);
});

Solution 2

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();
});
Share:
10,228

Related videos on Youtube

Jack Guy
Author by

Jack Guy

All the code you see in my snippets is hereby in the public domain. Enjoy.

Updated on September 09, 2022

Comments

  • Jack Guy
    Jack Guy over 1 year

    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.

  • Jack Guy
    Jack Guy over 10 years
    Thank you very much! I was almost there.
  • Andrey Belyak
    Andrey Belyak almost 6 years
    In your example captures is a list of results not a single value, is this expected value for req.user.id ?