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

例子: 我有URL http://www.somedomain.com/account/search?filter=a#top 但我只想要这一份 /账户/搜索

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


当前回答

如果你有一个抽象的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"

感谢jlong

其他回答

如果你有一个抽象的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"

感谢jlong

如果您想获取存储在变量中的URL的部分,我建议您使用URL- parse

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

根据文档内容,抽取了以下几个部分:

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,使用window.location.pathname,否则使用正则表达式:

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

有一个很有用的Web API方法叫做URL

const url =新的url ('https://www.somedomain.com/account/search?filter=a#top'); console.log (url.pathname.split(“/”).slice (1));//删除前导斜杠 const params = new URLSearchParams(url.search) console.log(“过滤:“,params.get(“过滤器”))

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

将为您提供一个包含所有URL部分的数组,您可以像正常数组一样访问它。

或者@Dylan提出了一个更优雅的解决方案,只有路径部分:

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