JavaScript – 获取URLpath的一部分

什么是正确的方式来拉出从JavaScript使用JavaScript的path?

例:
我有url
http://www.somedomain.com/account/search?filter=a#top
但我只想得到这部分
/帐号/search

如果有任何可以利用的东西,我正在使用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 


更新,为任何url使用相同的属性:

事实certificate,这个模式正在被标准化为一个叫做URLUtils的接口,你猜怎么着? 现有的window.location对象和锚点元素都实现了这个接口。

所以你可以使用上面的任何 URL的相同属性 – 只需创build一个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 。 我没有要testing的Internet Explorer版本,所以请使用JSFiddle示例进行testing。

JSFiddle示例

还有一个即将到来的URL对象,它将为URL本身提供这种支持,而不需要锚元素。 看起来像目前没有稳定的浏览器支持它,但据说它将在Firefox 26中出现 。 当你认为你可能会支持它时,请在这里尝试一下 。

 window.location.href.split('/'); 

将给你一个数组包含所有的url部分,你可以像一个普通的数组访问。

如果这是当前的 URL使用window.location.pathname,否则使用这个正则expression式:

 var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/; var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1]; 

其他答案都使用document.createElement或window.location,这是在节点环境中不支持的,所以我写了一个组件 ,可以在服务器端JavaScript以及浏览器中使用。

你可以使用parseUrl()来获得一个类似Nicole答案的对象:

 var url = 'http://www.somedomain.com/account/search?filter=a#top'; var urlObject = parseUrl(url); urlObject.href // 'http://www.somedomain.com/account/search?filter=a#top' urlObject.searchParams // { filter: 'a' } urlObject.hash // '#top' urlObject.search // '?filter=a' urlObject.protocol // 'http:' urlObject.host // 'www.somedomain.com' urlObject.hostname // 'www.somedomain.com' urlObject.port. // '' urlObject.path // '/account/search' 

随意导入组件以使用parseUrl()方法。