简体   繁体   English

在javascript参数之前得到一部分url

[英]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.我有一个 url('https://xyz.abc.org.com/v1.5/wth/data/analysis/geo?run=run1&aaa=some')直到'v1.5'直到任何api来电。

So I need to get the last part 'geo' out of the url.所以我需要从 url 中取出最后一部分“geo”。

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'.但是,这会返回 - 'geo?run=run1&aaa=some',而我想要 '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.此外,我不能使用一些数字来获取 substring,因为 url 的那部分对于不同的 api 调用会有所不同。

I just need the part of the url after last '/' and before '?'我只需要最后一个“/”之后和“?”之前的 url 的一部分or '&'.要么 '&'。

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

This will work whether there is a parameter list or not:无论是否有参数列表,这都将起作用:

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

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.无论哪种方式,如果它是一次性操作,则差异可以忽略不计,而且我会使用第一个 go,因为它更干净。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM