JavaScript - 获取 URL 路径的一部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6944744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 23:53:38  来源:igfitidea点击:

JavaScript - Get Portion of URL Path

javascriptjqueryurl

提问by BuddyJoe

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

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

Example:
I have URL
http://www.somedomain.com/account/search?filter=a#top
but I would just like to get this portion
/account/search

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

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

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

回答by Nicole

There is a property of the built-in window.locationobject 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? Both the existing window.locationobject and anchor elementsimplement the interface.

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

So you can use the same properties above for anyURL— 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. I do not have versions of Internet Explorer to test, so please test yourself with the JSFiddle example.

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

JSFiddle example

JSFiddle 示例

There's also a coming URLobject that will offer this support for URLs themselves, without the anchor element. 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.

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

回答by Jose Faeti

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('/');

回答by nobody

If this is the currenturl use window.location.pathnameotherwise use this regular expression:

如果这是当前url 使用window.location.pathname否则使用这个正则表达式:

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

回答by mplungjan

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"))

回答by Marian Klühspies

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:

protocol: The protocol scheme of the URL (e.g. http:). slashes: A boolean which indicates whether the protocol is followed by two forward slashes (//). auth: Authentication information portion (e.g. username:password). username: Username of basic authentication. password: Password of basic authentication. host: Host name with port number. hostname: Host name without port number. port: Optional port number. pathname: URL path. query: Parsed object containing query string, unless parsing is set to false. hash: The "fragment" portion of the URL including the pound-sign (#). href: The full URL. origin: The origin of the URL.

返回的 url 实例包含以下属性:

协议:URL 的协议方案(例如 http:)。斜杠:一个布尔值,指示协议后面是否跟有两个正斜杠 (//)。auth:认证信息部分(例如用户名:密码)。username:基本认证的用户名。password:基本认证密码。主机:带有端口号的主机名。hostname:不带端口号的主机名。端口:可选端口号。路径名:URL 路径。查询:包含查询字符串的解析对象,除非解析设置为 false。hash:URL 的“片段”部分,包括井号 (#)。href:完整网址。来源:URL 的来源。

回答by krolovolk

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