Siva Kannan
Siva Kannan

Reputation: 2471

regular expression for a url in node.js express routing

I am working on building node.js server which uses regular expression for routing.

The URL which has to captured in node.js using regex

www.domain.com/people-images-taken-on-December-05-2011/ 

The people-images-taken-on- is fixed in the URL. I only wanted to capture month, date and year.

I will capturing the above URL in express like below

app.get('/people-images-taken-on-{only alphabets}-{2 digits}-{4 digits} ',

I found the regex each patterns separately

allows only alphabets - [a-zA-Z]+$
allows a 4 digits value - (\\d){4}
allows a 2 digits value - (\\d){2}

I tried to combine everything, But I failed miserably many times. Can any one give the correct regex for the url patern? Also can anyone tell me this regex based path handling is a good way for handling Dates?

Upvotes: 1

Views: 940

Answers (1)

robertklep
robertklep

Reputation: 203286

You can use named parameters with custom regular expressions, like this:

app.get('/people-images-taken-on-:month([a-zA-Z]+)-:day(\\d{2})-:year(\\d{4})', ...)

This will store the values in req.params like this:

{ month: 'December', day: '05', year: '2011' }

Upvotes: 4

Related Questions