How to get current url without page in javascript

2020-06-19 06:54发布

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

3条回答
男人必须洒脱
2楼-- · 2020-06-19 07:30

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.

查看更多
\"骚年 ilove
3楼-- · 2020-06-19 07:50

Use window.location and substring.

location.href.substring(0, location.href.lastIndexOf("/"))
查看更多
ら.Afraid
4楼-- · 2020-06-19 07:57

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)
查看更多
登录 后发表回答