15

如何获取当前站点的 URL 路径,但没有最后一段:

http://www.domain.com/first/second/last

我只需要http://www.domain.com/first/second……使用 jQuery(或只有 JavaScript)

4

4 回答 4

21

使用 pop 和 URL api

这假设 URL 不太可能改变

我使用document.URL因为这是推荐的

const url = new URL("https://www.example.com/first/second/last"); // new URL(document.URL)
let path = url.pathname.split("/");
path.pop(); // remove the last
url.pathname = path.join("/")
console.log(url)

较旧的答案:根据 OP 的要求 - 更改评论

const url = "http://www.example.com/first/second/last", // document.URL, 
    shortUrl=url.substring(0,url.lastIndexOf("/"));
console.log(shortUrl)    

这是一个替代方案

const url = new URL("http://www.example.com/first/second/last"),
      shortUrl = `${url.protocol}//${url.hostname}${url.pathname.slice(0,url.pathname.lastIndexOf("/"))}`

console.log(shortUrl)

于 2012-12-12T18:14:58.587 回答
5

http://jsfiddle.net/KZsEW

为所有浏览器尝试以下操作:

var url = "http://www.domain.com/first/second/last";  // or var url = document.URL;
var subUrl = url.substring(0,url.lastIndexOf("/"))

alert(subUrl);
​

lastIndexOf()方法返回指定值在字符串中最后一次出现的位置。

注意:字符串从尾到头搜索,但返回从头开始的索引,位置为 0。

如果要搜索的值从未出现,则此方法返回 -1。

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/lastIndexOf

于 2012-12-12T17:44:31.597 回答
0

我不确定这是最优雅的解决方案,但您只希望子字符串到最后一个斜杠,或者如果最后一个字符是斜杠,则倒数第二个。在这里,我首先获取出现在协议(http:// 或 https://)之后的 URL 部分,以便在例如http://stackoverflow.com上返回http://stackoverflow.com

    var url = document.URL.split('://');
    var last_slash;
    var result;
    if (url[1].charAt(url[1].length - 1) === '/') {
      url[1] = url[1].substring(0, url[1].length - 1);
    }
    last_slash = url[1].lastIndexOf('/');
    result = url[0] + '://' + ((last_slash !== -1) ? url[1].substring(0, last_slash) : url[1]);

编辑:jsfiddle http://jsfiddle.net/CV6d4/

于 2012-12-12T17:47:59.887 回答
0

试试这个:

var url = 'http://www.domain.com/first/second/last';
for(var i=url.length-1; i>=0;i--){
    if(url[i]!='/'){
        url= url.substr(0,i);
    }
    else{
        alert(url);
        break;
    }
}
于 2012-12-12T18:05:49.080 回答