Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 487
user770252 Avatar asked Jan 25 '12 04:01

user770252


2 Answers

You can try this.

var url = location.protocol + "//" + document.domain + "/" 
          + location.pathname.split('/')[1] + "/";
like image 86
ShankarSangoli Avatar answered Oct 19 '22 18:10

ShankarSangoli


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 :) }

like image 40
Amar Palsapure Avatar answered Oct 19 '22 18:10

Amar Palsapure