使用 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('/');
如果这是当前url 使用window.location.pathname否则使用这个正则表达式:
var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];
有一个有用的 Web API 方法叫做URL
const url = new URL('http://www.somedomain.com/account/search?filter=a#top');
console.log(url.pathname.split('/'));
const params = new URLSearchParams(url.search)
console.log(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