0

I've a url ('https://xyz.abc.org.com/v1.5/wth/data/analysis/geo?run=run1&aaa=some') which remains the same till 'v1.5' till any api calls.

So I need to get the last part 'geo' out of the url.

Here's my code:

var testUrl = 'https://xyz.abc.org.com/v1.5/wth/data/analysis/geo?run=run1&aaa=some';
console.log(testUrl.substring(testUrl.lastIndexOf('/')));

But, this returns - 'geo?run=run1&aaa=some', while I want 'geo'.

How do I fix this?

Also, I can't use some numbers to get the substring out of it, as that part of the url will be different for different api calls.

I just need the part of the url after last '/' and before '?' or '&'.

Sunny
  • 902
  • 3
  • 18
  • 41
  • Does this answer your question? [Get path and query string from URL using javascript](https://stackoverflow.com/questions/16376438/get-path-and-query-string-from-url-using-javascript) – Nadin Hermann Oct 07 '20 at 07:06

3 Answers3

4

Last index of / and first index of ?. In between these is the text you require

var testUrl = 'https://xyz.abc.org.com/v1.5/wth/data/analysis/geo?run=run1&aaa=some';
console.log(testUrl.substring(testUrl.lastIndexOf('/')+1, (testUrl.indexOf('?') > testUrl.lastIndexOf('/') + 1)) ? testUrl.indexOf('?')  : testUrl.length ); 

// prints geo
AhmerMH
  • 638
  • 7
  • 18
0

This will work whether there is a parameter list or not:

testUrl.substring(testUrl.lastIndexOf('/')+1, testUrl.indexOf('?') > 0 ? testUrl.indexOf('?') : testUrl.length)
ollitietavainen
  • 3,900
  • 13
  • 30
0

Why not just get rid of everything starting from the question mark? You can modify the string you already have.

var testUrl = "https://xyz.abc.org.com/v1.5/wth/data/analysis/geo?run=run1&aaa=some";
var extractWithParams = testUrl.substring(testUrl.lastIndexOf('/'));
var extractWithoutParams = extractWithParams.split("?")[0];
console.log(extractWithoutParams);

// you could just do in all in one go,
// but i wrote it that way to make it clear what's going on
// testUrl.substring(testUrl.lastIndexOf('/')).split("?")[0];

Alternatively, you could also try

var extractWithParams = testUrl.substring(testUrl.lastIndexOf('/'));
var n = extractWithParams.indexOf("?"); // be careful. there might not be a "?"
var extractWithoutParams = extractWithParams.substring(0, n != -1 ? n : s.length);

I'm not sure which one performs better, but I'd imagine that the first one might be slower since it involves array operations. I might be wrong on that. Either way, if it's a one-time operation, the difference is negligible, and I'd go with the first once since it's cleaner.

audrey
  • 61
  • 7