0101 0101 - 7 months ago 18
Javascript Question

ExpressJS - Regex for matching a path doesn't work

I have a simple regex that should match words made of letters (0-5) only however it doesn't seems to be working. How should the regex look and be used in ExpressJS? URL I am trying to validate may look like

something.com/abcd


var express = require("express"),
app = express();

app.get("/:id(^[a-z]{0,5}$)", function(req, res) {
res.send("The right path!");
});

app.listen(8000);

Answer

To set up an URL which accepts / followed by up to five ascii characters, you could do like this:

var express = require("express"),
app = express();

app.get("/[a-z]{0,5}$", function(req, res){
    res.send("Right path!");
});
app.listen(8000);

result:

GET http://localhost:8000/
Right path!

GET http://localhost:8000/abcde
Right path!

GET http://localhost:8000/abcdef
Cannot GET /abcdef

Note: Express does case insensitive routing by default. To change it, put this at the top of your script:

app.set('case sensitive routing', true);

Now, [a-z] will match only lower case characters: GET /abc but not GET /ABC