0

I can't find the full pattern behind route parameters and regular expressions expressjs.

This matches:

route: exemple.com/users/123456

// Regex rule for route parameter
app.get( '^/users/:userId([0-9]{6})', function( req, res ) {
    res.send( 'Route match for User ID: ' + req.params.userId );
} );

This doesn't match:

route: exemple.com/us-en

app.use('/:countryAndLanguage(\w{2}-\w{2})',homepageRouter);

What am i not seeing..

Fabian
  • 443
  • 4
  • 12
  • 1
    Not an express user, but the expression looks fine to me. Do you get a value for the key when you try to log it? `app.use('/:countryAndLanguage(\w{2}-\w{2})', function (req, res, next) { console.log('key:', req.params.countryAndLanguage); next(); });` – oriberu Mar 29 '20 at 16:42
  • Thank you for your responds. It does not reach the console.log function you created. When i do remove the regex part i get the prop and key value. app.use('/:countryAndLanguage', function (req, res, next) { console.log('key:', req.params.countryAndLanguage); next(); }); wft is going on here. – Fabian Mar 29 '20 at 17:05
  • This does work. app.use('/:countryAndLanguage([0-9a-z-]+)',homepageRouter); – Fabian Mar 29 '20 at 17:14
  • Omg. Fixed it. I will answer my own question. – Fabian Mar 29 '20 at 17:19
  • Weird. Since Express seems to create a JavaScript regex object in the background, `\w{2}` should be supported. You can test expressions against routes [here](https://forbeslindesay.github.io/express-route-tester/). Maybe an Express version issue? Or maybe one of your other routes already reacts to strings formed like `/us-en`? – oriberu Mar 29 '20 at 17:20

1 Answers1

0

The documentation says the following:

Because the regular expression is usually part of a literal string, be sure to escape any \ characters with an additional backslash, for example \d+.

source: https://expressjs.com/en/guide/routing.html

So it was just a simple escape that I forgot.. . Finale answer:

app.use('/:countryAndLanguage(\\w{2}-\\w{2})',homepageRouter);
Fabian
  • 443
  • 4
  • 12