2

I want a super simple filter in nodejs express routing path. The param must be word1 or word2. Tested in: https://forbeslindesay.github.io/express-route-tester/

with expression: test/:gender(\b(word1|word2)\b)

path: test/word2

And all works well. "The path matches the route"

But in code:

router.get('^/test/:gender(\b(word1|word2)\b)', function (req, res, next){//something})...;

I got 404(redirects from express, as it should if the param is not correct!).

Note 1: removing the regex string, it works.

Note 2: another filter I DID managed to make it work. It has to be like: "word1-word2[-moreWords]. I implemented it with

router.get('^/test/:user_name(*[a-zA-Z0-9][-]*[a-zA-Z0-9])', function (req, res, next) {//something});

and works without problem.

Note 3: I also test it (I write them first in:) https://regex101.com/ and, of course, they work.

So what do I do wrong?

6
  • you may have config missing at express please provide us with express configuration like port,context Commented Jul 19, 2018 at 14:38
  • 1
    Try '^/test/:gender(word1|word2)\\b' or '^/test/:gender(word1|word2)\b' Commented Jul 19, 2018 at 14:38
  • 1
    @WiktorStribiżew It worked! with the \\b! Great, thanks! Now please teach me, why it works in express routing test and not in code? This was just an example but I will use many regex to prevent wrong/malicious insertions and some of them more complex. Any tips on how/where to write and test them so that they do work in code as well? P.S. can you write it as reply so I can close the question? Commented Jul 19, 2018 at 14:49
  • @BasilBattikhi Can port influence regex? If port was wrong, I would get browser 404 (not express - as it should) on anything, right? Commented Jul 19, 2018 at 14:53
  • @SharpBCD i don't think so but u thought that you may hitting on different port Commented Jul 19, 2018 at 14:55

1 Answer 1

2

You may use

'^/test/:gender(word1|word2)\\b'

Note that there is no word boundary between gender and word, you can only keep the trailing word boundary.

To define a word boundary, you need a literal backslash followed with b, so inside a string literal, you should write two consecutive backslash symbols.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.