Anders Östman
Anders Östman

Reputation: 3832

Regex in Express.js router

I'm trying to find some documentation about regex in Express, but the information in Express API is very sparse. I'm trying to do a regex matching objectID. This example about regex is given in the Express documentation.

router.get(/^\/commits\/(\w+)(?:\.\.(\w+))?$/, function(req, res){ ... });    

I have tried the following in my router, and it seems to work fine.

client.get('/staff/:id([0-9a-fA-F]{24})', function(req, res) { ... }); 

But there are some differences that i can't figure out...

Also, does anyone know about a extensive resource for reading about regex in Express routers... or parameter options or whatever it is I'm doing above...

Upvotes: 1

Views: 498

Answers (1)

deitch
deitch

Reputation: 14581

It is worth reading the source code for the route matching, but here is the short form.

  • 'abc' is a JS string; /abc/ is a JS regex. The string can be used to create a regex, which is what you are doing. So both are valid. To see the difference, try doing var re = /abc/ and var re = new RegExp('abc')
  • ^ is a starting anchor while $ is an ending anchor. ^abc will match "abc", "abcde" but not "zabcd" because it needs to start with "abc". abc$ will match "abc", "zabc" but not "abcd", because it needs to end with "abc".
  • when you use an actual RegExp expression starting with / and ending with /, if you want to use slashes in your RegExp, you need to escape them, else how will the interpreter know that this is a slash character and not the end of your RegExp? If you are using a string, it knows it is not, and so you do not need to escape.

For the last, try this:

"abc".match(/abc/);  // works
"abc".match('/abc/');  // fails because there are no slashes
"/abc/".match('/abc/');  // works
"/abc/".match(/abc/);  // works because "abc" is in there

Of course, you can escape the slashes, if you so choose

"/abc/".match('\/abc\/');  // works
"abc".match('\/abc\/');  // fails

Upvotes: 1

Related Questions