javascript 如何在javascript或jquery中获取没有页面的当前url

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16417791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 04:34:42  来源:igfitidea点击:

How to get current url without page in javascript or jquery

javascriptjqueryurl

提问by lawphotog

How can I get current URL without page in Javascript or jQuery.

如何在 Javascript 或 jQuery 中获取没有页面的当前 URL。

For example, if the url is:

例如,如果网址是:

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

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

I want to get the full path without the page so like:

我想获得没有页面的完整路径,例如:

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

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

No need to worry about parameters.

无需担心参数。

Thanks

谢谢

回答by Adil

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

您可以使用substring()来提取 url 的所需部分。

Live Demo

现场演示

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

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

您可以使用 window.location.href 获取当前 url

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

回答by PurkkaKoodari

Use window.locationand substring.

使用window.locationsubstring

location.href.substring(0, location.href.lastIndexOf("/"))

回答by bladnman

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:

这将返回整个 URL (href) 直到最后一个目录,包括尾部斜杠。我通过访问站点并在控​​制台中删除该函数然后调用它,在一堆不同的 URL 上对其进行了测试。一些例子和结果:

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.

最后一个是这个页面。