本文介绍了JavaScript - 获取 URL 路径的一部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 JavaScript 从 URL 中提取路径的正确方法是什么?

What is the correct way to pull out just the path from a URL using JavaScript?

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

如果有任何可以利用的东西,我正在使用 jQuery.

I am using jQuery if there is anything there that can be leveraged.

推荐答案

有一个内置的属性 window.location 对象,将为当前窗口提供该对象.

There is a property of the built-in window.location object that will provide that for the current window.

// 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,你猜怎么着?现有的window.location 对象和锚元素都实现了该接口.



Update, use the same properties for any URL:

It turns out that this schema is being standardized as an interface called URLUtils, and guess what? Both the existing window.location object and anchor elements implement the interface.

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

So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:

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

[1]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right

这适用于最新版本的 Chrome 和 Firefox.我没有要测试的 Internet Explorer 版本,因此请使用 JSFiddle 示例进行测试.

This works in the latest versions of Chrome and Firefox. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.

还有一个即将到来的URL 对象,它将为 URL 本身提供这种支持,没有锚元素.目前看起来没有稳定的浏览器支持它,但据说它会在 Firefox 26 中出现.当你认为您可能对此有支持,请在此处试用.

这篇关于JavaScript - 获取 URL 路径的一部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 16:44