简体   繁体   English

JavaScript - 获取 URL 路径的一部分

[英]JavaScript - Get Portion of URL Path

What is the correct way to pull out just the path from a URL using JavaScript?使用 JavaScript 从 URL 中提取路径的正确方法是什么?

Example:例子:
I have URL我有 URL
http://www.somedomain.com/account/search?filter=a#top http://www.somedomain.com/account/search?filter=a#top
but I would just like to get this portion但我只想得到这部分
/account/search /帐户/搜索

I am using jQuery if there is anything there that can be leveraged.如果有任何可以利用的东西,我正在使用 jQuery。

There is a property of the built-in window.location object that will provide that for the current window.内置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  


Update, use the same properties for any URL:更新,对任何 URL 使用相同的属性:

It turns out that this schema is being standardized as an interface called URLUtils , and guess what?事实证明,这个模式被标准化为一个名为URLUtils的接口,你猜怎么着? Both the existing window.location object and anchor elements implement the interface.现有的window.location对象和锚元素都实现了该接口。

So you can use the same properties above for any URL — just create an anchor with the URL and access the properties:所以你可以对任何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]: Browser support for the properties that include port is not consistent, See: http://jessepollak.me/chrome-was-wrong-ie-was-right [1]:浏览器对包含端口的属性的支持不一致,参见: http : //jessepollak.me/chrome-was-wrong-ie-was-right

This works in the latest versions of Chrome and Firefox .这适用于最新版本的 Chrome 和 Firefox I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.我没有要测试的 Internet Explorer 版本,因此请使用 JSFiddle 示例进行测试。

JSFiddle example JSFiddle 示例

There's also a coming URL object that will offer this support for URLs themselves, without the anchor element.还有一个即将到来的URL对象,它将为 URL 本身提供这种支持,没有锚元素。 Looks like no stable browsers support it at this time, but it is said to be coming in Firefox 26. When you think you might have support for it, try it out here .目前看起来没有稳定的浏览器支持它,但据说它会在 Firefox 26 中出现当您认为您可能支持它时,请在此处尝试

window.location.href.split('/');

Will give you an array containing all the URL parts, which you can access like a normal array.将为您提供一个包含所有 URL 部分的数组,您可以像普通数组一样访问它。

Or an ever more elegant solution suggested by @Dylan, with only the path parts:或者@Dylan 建议的更优雅的解决方案,只有路径部分:

window.location.pathname.split('/');

If this is the current url use window.location.pathname otherwise use this regular expression:如果这是当前url 使用window.location.pathname否则使用这个正则表达式:

var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];

There is a useful Web API method called URL有一个有用的 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"))

If you have an abstract URL string (not from the current window.location ), you can use this trick:如果你有一个抽象的 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"

Thanks to jlong感谢jlong

In case you want to get parts of an URL that you have stored in a variable, I can recommend URL-Parse如果您想获取存储在变量中的URL 的一部分,我可以推荐URL-Parse

const Url = require('url-parse');
const url = new Url('https://github.com/foo/bar');

According to the documentation, it extracts the following parts:根据文档,它提取了以下部分:

The returned url instance contains the following properties:返回的 url 实例包含以下属性:

protocol: The protocol scheme of the URL (eg http:).协议:URL 的协议方案(例如 http:)。 slashes: A boolean which indicates whether the protocol is followed by two forward slashes (//).斜杠:一个布尔值,指示协议后面是否跟有两个正斜杠 (//)。 auth: Authentication information portion (eg username:password). auth:认证信息部分(例如用户名:密码)。 username: Username of basic authentication. username:基本认证的用户名。 password: Password of basic authentication. password:基本认证密码。 host: Host name with port number.主机:带有端口号的主机名。 hostname: Host name without port number. hostname:不带端口号的主机名。 port: Optional port number.端口:可选端口号。 pathname: URL path.路径名:URL 路径。 query: Parsed object containing query string, unless parsing is set to false.查询:包含查询字符串的解析对象,除非解析设置为 false。 hash: The "fragment" portion of the URL including the pound-sign (#). hash:URL 的“片段”部分,包括井号 (#)。 href: The full URL. href:完整网址。 origin: The origin of the URL.来源:URL 的来源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM