【问题标题】:How to get current url without page in javascript or jquery如何在javascript或jquery中获取没有页面的当前url
【发布时间】:2013-05-07 11:24:24
【问题描述】:

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

例如,如果url是:

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

我想得到没有页面的完整路径,比如:

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

无需担心参数。

谢谢

【问题讨论】:

  • window.location.hostname + window.location.pathname
  • @NickN。那篇文章是关于删除参数的。答案仍然有我希望删除的页面名称。谢谢。

标签: javascript jquery url


【解决方案1】:

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

Live Demo

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

你可以使用window.location.href来获取当前的url

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

【讨论】:

  • +1 最好这样写:url.substring(0, url.lastIndexOf('/')+1);
  • 谢谢@Siamak.A.M,你真好。
【解决方案2】:

使用window.locationsubstring

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

【讨论】:

  • 如果参数包含"/",则此答案将是错误的:test.com/path/?para=this/bad
【解决方案3】:

这些答案都很好。为了其他后来来到这里并想要一个完全封装的答案的人,我想我会整合一个函数

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;
};

这将返回整个 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/"

最后一个就是这个页面。

【讨论】:

    猜你喜欢
    • 2011-10-24
    • 2017-08-23
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    相关资源
    最近更新 更多