I want to use jQuery to get the location and the first folder with window.location
Asked Answered
C

4

8

I want to get the location and the first folder, like:

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

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

this returns

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

So I would like it to return everything up to "test/", so I only end up with:

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

Thanks in advance!

Coloring answered 25/1, 2012 at 4:23 Comment(0)
A
16

You can try this.

var url = location.protocol + "//" + document.domain + "/" 
          + location.pathname.split('/')[1] + "/";
Assyria answered 25/1, 2012 at 4:30 Comment(1)
Worked like a charm! Much appreciated!Coloring
H
3

Try this

 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;
 }

Handles almost all the cases { I guess so :) }

Hewes answered 25/1, 2012 at 4:31 Comment(0)
C
2

In case there is something more useful you'd like to do using the Location Object I'd look at the docs first.

In any case, what I think you are looking for is something like this:

var href = location.href.split('/');
href.pop();
href = href.join('/') + '/';
console.log(href);
Cestus answered 25/1, 2012 at 4:46 Comment(0)
G
2

@Amar has an excellent answer, but just to demonstrate what you can do with javascript here is another solution. I do not know if it's recommended and if it isn't I'd like to hear why.

//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;
}

Used like this

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

See the fiddle: http://jsfiddle.net/giddygeek/zGQN2/1/

Gravy answered 25/1, 2012 at 5:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.