8

我想获取位置和第一个文件夹,例如:

http://www.example.com/test/

var $location = window.location.href;
alert ($location);

这返回

http://www.example.com/test/location-test.html

所以我希望它将所有内容都返回到“test/”,所以我只得到:

http://www.example.com/test/

提前致谢!

4

4 回答 4

15

你可以试试这个。

var url = location.protocol + "//" + document.domain + "/" 
          + location.pathname.split('/')[1] + "/";
于 2012-01-25T04:30:49.473 回答
3

试试这个

 function baseUrl() {

     var baseUri = window.location.href;
     //Removes any # from href (optional)
     if(baseUri.slice(baseUri.length - 1, baseUri.length) == "#")
          baseUri = baseUri.slice(0, baseUri.length - 1);
     var split = window.location.pathname.split('/');
     if (split.length > 2) 
          baseUri = baseUri.replace(window.location.pathname, '') + "/" + split[1] + "/";
     //This will append the last slash
     if (baseUri.substring(baseUri.length - 1, baseUri.length) != "/") 
          baseUri += "/";
     return baseUri;
 }

处理几乎所有的情况{我猜是这样:)}

于 2012-01-25T04:31:29.690 回答
2

如果您想使用位置对象做一些更有用的事情,我会先查看文档

无论如何,我认为您正在寻找的是这样的:

var href = location.href.split('/');
href.pop();
href = href.join('/') + '/';
console.log(href);
于 2012-01-25T04:46:21.867 回答
2

@Amar 有一个很好的答案,但只是为了演示您可以在这里使用 javascript 做什么是另一种解决方案。我不知道它是否被推荐,如果不是,我想听听为什么。

//Play with the sting prototype
String.prototype.getFirstFolder = function ()
{ //Get First Folder
    var parts = this.split('/');
    var ret = parts[0];//if parts.length is <=1 then its an invalid url
    var stop = Math.min(4,parts.length);
    for(i=1;i<stop;i++) {
        ret += "/" + parts[i];
    }
    return ret;
}

像这样使用

var str = "http://www.google.com/test/pages.html";
str.getFirstFolder();

见小提琴:http: //jsfiddle.net/giddygeek/zGQN2/1/

于 2012-01-25T05:12:35.407 回答