Bud*_*Joe 163 javascript url jquery
使用JavaScript从URL中提取路径的正确方法是什么?
示例:
我有URL
http://www.somedomain.com/account/search?filter=a#top
但我只想获得此部分
/帐户/搜索
我正在使用jQuery,如果有任何可以利用的东西.
Nic*_*ole 392
内置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
Run Code Online (Sandbox Code Playgroud)
事实证明,这个模式正在被标准化为一个名为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
Run Code Online (Sandbox Code Playgroud)
[1]:浏览器对包含端口的属性的支持不一致,请参阅:http://jessepollak.me/chrome-was-wrong-ie-was-right
这适用于最新版本的Chrome和Firefox.我没有要测试的Internet Explorer版本,所以请使用JSFiddle示例测试自己.
还有一个即将到来的URL
对象将为URL本身提供这种支持,而不需要锚元素.看起来目前还没有稳定的浏览器支持它,但据说它将在Firefox 26中出现. 如果您认为可能支持它,请在此处试试.
Jos*_*eti 47
window.location.href.split('/');
Run Code Online (Sandbox Code Playgroud)
将为您提供一个包含所有URL部分的数组,您可以像普通数组一样访问它们.
或@Dylan建议的更优雅的解决方案,只有路径部分:
window.location.pathname.split('/');
Run Code Online (Sandbox Code Playgroud)
nob*_*ody 28
如果这是当前 url,则使用window.location.pathname否则使用此正则表达式:
var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];
Run Code Online (Sandbox Code Playgroud)
mpl*_*jan 10
有一个有用的 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"))
Run Code Online (Sandbox Code Playgroud)
如果你有一个抽象的 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"
Run Code Online (Sandbox Code Playgroud)
感谢jlong
归档时间: |
|
查看次数: |
167744 次 |
最近记录: |