JavaScript - 获取URL路径的一部分
使用JavaScript从URL中提取路径的正确方法是什么?
What is the correct way to pull out just the path from a URL using JavaScript?
示例:
我有URL
http://www.somedomain.com/account/search?filter=a#top
但我想得到这部分
/ account / search
如果有任何可以利用的东西,我正在使用jQuery。
I am using jQuery if there is anything there that can be leveraged.
内置属性 window.location
对象这将为当前窗口提供。
There is a property of the built-in window.location
object that will provide that for the current window.
// If URL is http://www.somedomain.com/account/search?filter=a#top
window.location.pathname // /account/search
// For reference:
window.location.host // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash // #top
window.location.href // http://www.somedomain.com/account/search?filter=a#top
window.location.port // (empty string)
window.location.protocol // http:
window.location.search // ?filter=a
事实证明,这个模式正在被标准化为一个名为 URLUtils ,猜猜是什么?现有的 window.location
对象和锚元素都实现了界面。
It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location
object and anchor elements implement the interface.
因此,您可以使用上面相同的属性任何网址—只需使用URL创建一个锚并访问属性:
So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:
var el = document.createElement('a');
el.href = "http://www.somedomain.com/account/search?filter=a#top";
el.host // www.somedomain.com (includes port if there is one[1])
el.hostname // www.somedomain.com
el.hash // #top
el.href // http://www.somedomain.com/account/search?filter=a#top
el.pathname // /account/search
el.port // (port if there is one[1])
el.protocol // http:
el.search // ?filter=a
[1]:浏览器对包含端口的属性的支持不一致,请参阅: http://jessepollak.me/chrome-was-wrong-ie-was-right
[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right
适用于最新版本的Chrome和Firefox 。我没有要测试的Internet Explorer版本,所以请使用JSFiddle示例测试自己。
This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.
还有一个 URL
对象将为URL本身提供此支持,锚元素。看起来目前没有稳定的浏览器支持它,但据说它将在Firefox 26中使用。当你认为你可能会支持它,试试这里。