7

How can I 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 the page so like:

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

No need to worry about parameters.

Thanks

Tiago Sippert
1,3307 gold badges24 silver badges33 bronze badges
asked May 7, 2013 at 11:24
3
  • 1
    possible duplicate: stackoverflow.com/questions/9513736/… Commented May 7, 2013 at 11:27
  • 1
    window.location.hostname + window.location.pathname Commented May 7, 2013 at 11:30
  • @NickN. That post is about removing parameters. The answer still has the page name which I wish to remove. Thanks. Commented May 7, 2013 at 12:58

3 Answers 3

17

You can use substring() to extract the desired part of 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)
answered May 7, 2013 at 11:26
2
  • +1 and it's better to write like this: url.substring(0, url.lastIndexOf('/')+1); Commented May 7, 2013 at 11:31
  • Thanks @Siamak.A.M, so nice of you. Commented May 7, 2013 at 11:33
4

Use window.location and substring.

location.href.substring(0, location.href.lastIndexOf("/"))
answered May 7, 2013 at 11:27
1
  • This answer will be wrong if parameter contains "/": test.com/path/?para=this/bad Commented Aug 3, 2020 at 17:42
4

These answers are all good. For the sake of others who come by here later and want an entirely encapsulated answer I thought I'd pull 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) up to the last directory including a trailing slash. I tested it across a bunch of different URLs by visiting sites and dropping the function in the console then calling it. Some 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/"

That last one is this page.

answered Dec 1, 2013 at 18:19

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.