1

There are some APIs with some versions. i.e. 1. /v1/order/create 2. /order/v2/create

Their is common middleware going to invoke. In middleawre I need version of API (i.e. v1 or v2) to perform some specific task for specific version. I tried with below code but failing for 2nd type of url.

var pieces = req.url.replace(/^\/+/, '').split('/');
var version = pieces[0];
req.version =  version || 0;
Dharman
  • 30,962
  • 25
  • 85
  • 135
Dharmraj
  • 164
  • 1
  • 15
  • Do you need to get `2` in case of `/order/v2/create`? – Wiktor Stribiżew May 10 '17 at 14:22
  • Your router should be able to pick this apart for you, without you having to do it yourself. Routers parse endpoints for a living. –  May 10 '17 at 16:06
  • @WiktorStribiżew both will work either v2 or 2. But regex should work for both cases. – Dharmraj May 11 '17 at 05:37
  • @Dharmraj: Why did you accept a copy of my answer that was posted 3 minutes later than my answer? This hijacking practice should not be encouraged. `/\/v([0-9]+)\//` works the same as `/\/v(\d+)\//` since `\d` = `[0-9]`, but is longer. Also, please consider upvoting those answers you found helpful. – Wiktor Stribiżew May 11 '17 at 06:51
  • @WiktorStribiżew This question is unique, and something useful to a programmer like me who wanted a regex pattern for getting version from API. The question you are claiming this one is duplicating is not asking for a pattern for version, but a really broad question, which has also been closed. That question is about learning regex, which I am not looking to do right now. – Alan Ball Sep 23 '19 at 12:22

2 Answers2

2

Don't search from the beginning of the URL. Try something like:

var match = req.url.match(/\/v([0-9]+)\//);
var version = 0;
if (match) {
    version = match[1];
}
console.log(version); // outputs version number
Alex Schenkel
  • 728
  • 1
  • 7
  • 13
0

You can use this:

Regex: /\/(v\d+)\//

  • (v\d+) allows capturing v followed by a number of integers such as v1, v2, v123, v0 etc.
  • If you also want to allow decimal versioning, use /\/(v\d+.?\d*)\//. example: v1.1, v2.0 etc

var url = "/v1/order/create"
var pieces = url.match(/\/(v\d+)\//);
console.log(pieces[1]);
// Output is v1
degant
  • 4,861
  • 1
  • 17
  • 29