gpt4 book ai didi

JavaScript - 获取 URL 路径的一部分

转载 作者:IT老高 更新时间:2023-10-28 13:17:25 26 4
gpt4 key购买 nike

使用 JavaScript 从 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


更新,对任何 URL 使用相同的属性:

事实证明,这个模式正在被标准化为一个名为 URLUtils 的接口(interface)。 , 你猜怎么着?现有的 window.location 对象和 anchor 元素都实现了该接口(interface)。

因此您可以对 任何 URL 使用上述相同的属性 — 只需使用 URL 创建一个 anchor 并访问属性:

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 示例进行测试。

JSFiddle example

还有一个即将到来的URL将为 URL 本身提供这种支持的对象,没有 anchor 元素。看起来目前没有稳定的浏览器支持它,但据说它会在 Firefox 26 中出现。When you think you might have support for it, try it out here .

关于JavaScript - 获取 URL 路径的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6944744/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com