JavaScript - 获取 URL 路径的一部分
2022-08-30 00:46:57
使用JavaScript从URL中提取路径的正确方法是什么?
示例:
我有URL
http://www.somedomain.com/account/search?filter=a#top
,但我只想获得此部分
/帐户/搜索
我正在使用jQuery,如果那里有任何可以利用的东西。
使用JavaScript从URL中提取路径的正确方法是什么?
示例:
我有URL
http://www.somedomain.com/account/search?filter=a#top
,但我只想获得此部分
/帐户/搜索
我正在使用jQuery,如果那里有任何可以利用的东西。
内置 window.location
对象有一个属性,该属性将为当前窗口提供该属性。
// 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
因此,您可以对任何URL使用相同的属性 - 只需使用URL创建一个锚点并访问属性:
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
这适用于最新版本的Chrome和Firefox。我没有要测试的Internet Explorer版本,所以请使用JSFiddle示例测试自己。
还有一个即将到来的URL
对象,它将为URL本身提供这种支持,而无需锚点元素。目前似乎没有稳定的浏览器支持它,但据说它将在Firefox 26中推出。当您认为自己可能对此表示支持时,请在此处尝试一下。
window.location.href.split('/');
将为您提供一个包含所有URL部分的数组,您可以像普通数组一样访问这些部分。
或者@Dylan建议的更优雅的解决方案,只有路径部分:
window.location.pathname.split('/');