How to get current url without page in javascript or jquery

How to get current url without page in javascript or jQuery.

For example, if the URL is:

http://www.abc.com/music/pop.aspx

I want to get the full path without a page like this:

http://www.abc.com/music/

No need to worry about options.

thanks

+6
source share
3 answers

You can use substring () to extract the desired part of the URL.

Live demo

urlBase = url.substring(0, url.lastIndexOf('/')+1); 

You can use window.location.href to get the current URL

 urlBase = location.href.substring(0, location.href.lastIndexOf("/")+1) 
+12
source

Use window.location and substring .

 location.href.substring(0, location.href.lastIndexOf("/")) 
+4
source

These answers are good. For the sake of others who came here later and want a fully encapsulated answer, I thought I would put together a function

 function locationHREFWithoutResource() { var pathWORes = location.pathname.substring(0, location.pathname.lastIndexOf("/")+1); var protoWDom = location.href.substr(0, location.href.indexOf("/", 8)); return protoWDom + pathWORes; }; 

This will return the entire URL (href) to the last directory, including the trailing slash. I tested it at several URLs, visiting sites and dropping a function in the console, and then calling it. Example and results:

 http://meyerweb.com/eric/tools/dencoder/ -> "http://meyerweb.com/eric/tools/dencoder/" https://www.google.com/ -> "https://www.google.com/"` http://stackoverflow.com/questions/16417791/how-to-get-current-url-without-page-in-javascript-or-jquery -> "http://stackoverflow.com/questions/16417791/" 

The last page is the page.

+2
source

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


All Articles