Vikas
Vikas

Reputation: 985

Checking if url contains a number in express

I am making a middleware function in nodejs and express js framework and I want to check if the url contains a number in it or not just like this

/invoices/21 or /invoices/45

so I am trying to do something like this

 if (req.path.startsWith('/invoices/[^0-9]') {
    next();
  }  

but i am getting error I am still not able to do so can anyone give hint.

Upvotes: 1

Views: 2495

Answers (5)

Enoch Klu
Enoch Klu

Reputation: 1

Simplifying Naman's answer;

If you are checking for every single URL in a middleware which matches the condition, you could test that like so:

if (/^\/invoices\/(\d)+/.test(req.originalUrl)) {
    // Do something when condition is true
}

This assumes you are now using the latest version of Express.

Upvotes: 0

sfy
sfy

Reputation: 3238

  const re = /^\/invoices(\/.*)?\/\d*\//
  if(re.test(req.originalUrl.toLowerCase())) {
    // include a number
  }

//'/invoices/kk/190/foo' will pass
//'/invoices/kk/190k/foo' won't pass

What version of express are you using? I can only access the path via req.originalUrl, no req.path.

Upvotes: 0

guijob
guijob

Reputation: 4488

startsWith receives strings not regular expressions. You can use match in this situation.

var str = '/invoices/120';
if (str.match(/^\/invoices\/\d+/)) { // return truly value
  next(); // gets executed
} 

var str = '/invoices/abc';
if (str.match(/^\/invoices\/\d+/)) { // return falsy value
  next();
} 

You can check it out in jsfiddle.

Upvotes: 0

skiilaa
skiilaa

Reputation: 1282

You can't use a RegExp like that. startsWith only takes a string. This code creates a RegExp, and uses match to check if the string matches the RegExp.

if (req.path.match(new RegExp('/invoices/[^0-9]'))) { // create a regexp and check if it matches
    next();
} 

Upvotes: 0

Naman Kheterpal
Naman Kheterpal

Reputation: 1840

The fastest way is to check with RegExp

if(RegExp(/^\/invoices\/[0-9]/).test(req.path)){
    // do something
}

Upvotes: 2

Related Questions