如何使用JavaScript从URL中提取路径的正确方法?
例子:
我有一个URL
http://www.somedomain.com/account/search?filter=a#top
但我只想获取这部分
/account/search
如果有jQuery可以利用的话,我正在使用它。
如何使用JavaScript从URL中提取路径的正确方法?
例子:
我有一个URL
http://www.somedomain.com/account/search?filter=a#top
但我只想获取这部分
/account/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
事实证明,该模式正在被标准化为名为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('/');
var reg = /.+?:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];
/.+?\:\/\/.+?(\/.+?)?(?:#|\?|)?$/
。 - Scottmas有一个非常有用的 Web API 方法被称为 URL
const url = new URL('https://www.somedomain.com/account/search?filter=a#top');
console.log(url.pathname.split('/').slice(1)); // drop the leading slash
const params = new URLSearchParams(url.search)
console.log("filter:",params.get("filter"))
如果你有一个 URL 字符串(不是来自当前的 window.location
),可以使用这个技巧:
let yourUrlString = "http://example.com:3000/pathname/?search=test#hash";
let parser = document.createElement('a');
parser.href = yourUrlString;
parser.protocol; // => "http:"
parser.hostname; // => "example.com"
parser.port; // => "3000"
parser.pathname; // => "/pathname/"
parser.search; // => "?search=test"
parser.hash; // => "#hash"
parser.host; // => "example.com:3000"
感谢jlong
提供的帮助。const Url = require('url-parse');
const url = new Url('https://github.com/foo/bar');