2

Why this router works

app.get(/regularExpression/, function (req, res, next) {
});

But this don't work Cannot GET

var regularExpressionString = "regularExpressionString";    
var regularExpression = new RegExp(regularExpressionString);

app.get(regullarExpression, function (req, res, next) {
});

I need the second variant because I want to reuse router string parts according to DRY principle without repeating code. But when I use /regularExpression/ I cannot concat strings like /regularExpressionString1 + regularExpressionString2/.

So how to concat strings in node.js express regex route?

update

new RegExp works if I don't use special symbols like \d or \w

For example this pattern works:

regex = new RegExp('/(32)teeth')

But this don't:

regex = new RegExp('/(\d+)teeth')
Community
  • 1
  • 1
Maxim Yefremov
  • 13,671
  • 27
  • 117
  • 166
  • The second variant should work as well. Ensure that you navigate in your browser to `/regularExpressionString`, not just `/regularExpression` – Oleg Aug 08 '14 at 05:45
  • @CuriousGuy thank you. Simple regular expression like `new RegExp('/regularExpressionString')` really works. But when I try to use `\d` or `\s` it fails. `Cannot GET`. Please see my update above. – Maxim Yefremov Aug 08 '14 at 06:16

1 Answers1

3

You should escape \ symbol when using RegExp constructor, so it would be:

regex = new RegExp('/(\\d+)teeth')

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Oleg
  • 22,300
  • 9
  • 68
  • 84