Sunny
Sunny

Reputation: 932

Get part of a url in javascript before the parameters

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 '&'.

Upvotes: 0

Views: 644

Answers (3)

audrey
audrey

Reputation: 61

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.

Upvotes: 0

AhmerMH
AhmerMH

Reputation: 688

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

Upvotes: 4

ollitietavainen
ollitietavainen

Reputation: 4275

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

testUrl.substring(testUrl.lastIndexOf('/')+1, testUrl.indexOf('?') > 0 ? testUrl.indexOf('?') : testUrl.length)

Upvotes: 0

Related Questions