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

I want to get the location and the first folder, for example:

http://www.example.com/test/ var $location = window.location.href; alert ($location); 

it returns

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

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

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

Thanks in advance!

+6
source share
4 answers

You can try this.

 var url = location.protocol + "//" + document.domain + "/" + location.pathname.split('/')[1] + "/"; 
+12
source

try it

  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 cases {I think so :)}

+2
source

In case you want to do something more useful using the Location object, I would first look at the documents .

Anyway, I think what you're looking for is something like this:

 var href = location.href.split('/'); href.pop(); href = href.join('/') + '/'; console.log(href); 
+1
source

@Amar has a great answer, but just to demonstrate what you can do with javascript, this is another solution. I do not know if he recommended, and if it is not, I would 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 as

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

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

+1
source

Source: https://habr.com/ru/post/906814/


All Articles