Costa Michailidis
Costa Michailidis

Reputation: 8178

How to match two strings to one route express.js

I've got a single route function that I want to match two different paths to. The idea is to create profile pages for team members of a website. They'll be at www.domain.com/name. The issue is, some people have nicknames. So, I need www.domain.com/nickname to go to the same place as www.domain.com/name.

Here's what I've got so far:

website.get('/name|nickname', websiteRoutes.about);

The problem is things like /asdasdfdnickname and /namezzzzzzzz will match as well.

How do I match either the name or nickname only without any extra characters. I believe this is called an exclusive or?

So here are some working solutions

Passing in ['/name', '/nickname'] into the routing function.

And from John's answer below: /^\/?(name|nickname)\/?$/i

Upvotes: 4

Views: 1029

Answers (1)

John Strom
John Strom

Reputation: 81

Try /^\/?(name|nickname)\/?$/i which will match exactly name/nickname only.

This regex means it can optionally start with a forward slash, it will match "name" or "nickname" case insensitively, then it will optionally allow another forward slash at the end.

Upvotes: 4

Related Questions