user7499416
user7499416

Reputation:

Express: match route for language code in url

I'm trying to capture an optional :lang? param of two charachters for this routes:

/             // lang: undefined
/en           // lang: en
/projects     // lang: undefined
/en/projects  // lang: en

This is my try:

router.get('/:lang([a-z]{2})?*', function(req, res, next) {

}

But for /projects it sets a :lang? parameter as pr.

How can I avoid that?

Upvotes: 1

Views: 195

Answers (1)

falinsky
falinsky

Reputation: 7428

To beat this issue you can try to use the next pattern:

/:lang([a-z]{2})?/:rest(*)?

Here another optional param rest is introduced to capture such a trailing.

You can check live examples:

Upvotes: 1

Related Questions