如何在 JavaScript 中解析 URL:主机名、路径名、查询、哈希

121 篇文章 7 订阅

Post cover

 

统一资源定位器,缩写为URL,是对网络资源(网页、图像、文件)的引用。URL 指定资源位置和检索资源的机制(http、ftp、mailto)。

例如,这是这篇博文的 URL:

 
https://dmitripavlutin.com/parse-url-javascript

通常,您需要访问 URL 的特定组件。这些可能是主机名(例如dmitripavlutin.com)或路径名(例如/parse-url-javascript)。

访问 URL 组件的一个方便的解析器是URL()构造函数。

在这篇文章中,我将向您展示 URL 的结构及其主要组件。

然后,我将描述如何使用URL()构造函数轻松选择 URL 的组件,如主机名、路径名、查询或哈希。

1. 网址结构

一张价值一千字的图像。没有太多文字说明,在下图中您可以找到 URL 的主要组成部分:

JavaScript 中的 URL() 构造函数组件

2. URL()构造函数

URL()是constuctor功能,可以让一个URL的组成部分的解析:

 
const url = new URL(relativeOrAbsolute [, absoluteBase]);

relativeOrAbsolute参数可以是绝对或相对 URL。如果第一个参数是相对的,那么第二个参数absoluteBase是必需的,并且必须是作为第一个参数的基础的绝对 URL。

例如,让我们URL()使用绝对 URL 进行初始化:

 
const url = new URL('http://example.com/path/index.html');
url.href; // => 'http://example.com/path/index.html'

或结合相对和绝对 URL:

 
const url = new URL('/path/index.html', 'http://example.com');
url.href; // => 'http://example.com/path/index.html'

实例的href属性URL()返回整个 URL 字符串。

创建后URL()的实例,您可以访问提出的任何URL组件上一张图片。作为参考,这里是URL()实例接口:

interface URL {

href: USVString;

protocol: USVString;

username: USVString;

password: USVString;

host: USVString;

hostname: USVString;

port: USVString;

pathname: USVString;

search: USVString;

hash: USVString;

readonly origin: USVString;

readonly searchParams: URLSearchParams;

toJSON(): USVString;

}

其中USVString类型映射到一个字符串时,在JavaScript中返回。

3. 查询字符串

url.search属性访问以 为前缀的 URL 的查询字符串?

 
const url = new URL(
'http://example.com/path/index.html?message=hello&who=world'
);
url.search; // => '?message=hello&who=world'

如果缺少查询字符串,则url.search计算为空字符串''

 
const url1 = new URL('http://example.com/path/index.html');
const url2 = new URL('http://example.com/path/index.html?');
url1.search; // => ''
url2.search; // => ''

3.1 解析查询字符串

比访问原始查询字符串更方便的是访问查询参数。

选择查询参数的一种简单方法是提供url.searchParams属性。此属性包含URLSearchParams 的一个实例。

URLSearchParamsobject 提供了许多方法(如get(param)has(param))来访问查询字符串参数。

让我们看一个例子:

 
const url = new URL(
'http://example.com/path/index.html?message=hello&who=world'
);
url.searchParams.get('message'); // => 'hello'
url.searchParams.get('missing'); // => null

url.searchParams.get('message')返回message查询参数的值— 'hello'

但是,访问不存在的参数的url.searchParams.get('missing')计算结果为null

4.主机名

url.hostname 属性包含 URL 的主机名:

 
const url = new URL('http://example.com/path/index.html');
url.hostname; // => 'example.com'

5.路径名

url.pathname 属性访问 URL 的路径名:

 
const url = new URL('http://example.com/path/index.html?param=value');
url.pathname; // => '/path/index.html'

如果 URL 没有路径,则该url.pathname属性返回一个斜杠字符/

 
const url = new URL('http://example.com/');
url.pathname; // => '/'

6.哈希

最后,可以使用url.hash属性访问散列:

 
const url = new URL('http://example.com/path/index.html#bottom');
url.hash; // => '#bottom'

当 URL 中的哈希丢失时,url.hash计算结果为空字符串''

 
const url = new URL('http://example.com/path/index.html');
url.hash; // => ''

7. 网址验证

new URL()构造函数创建一个实例时,作为副作用,它还会验证 URL 的正确性。如果 URL 值无效,TypeError则抛出 a。

例如,http ://example.com是无效的 URL,因为http.

让我们使用这个无效的 URL 来初始化解析器:

 
try {
const url = new URL('http ://example.com');
} catch (error) {
error; // => TypeError, "Failed to construct URL: Invalid URL"
}

因为'http ://example.com'是一个无效的 URL,正如预期的那样,new URL('http ://example.com')抛出一个TypeError.

8. 网址操作

除了访问URL成分,性质一样searchhostnamepathnamehash是可写的-因此你可以操纵的URL。

例如,让我们将现有 URL 的主机名从 修改red.comblue.io

 
const url = new URL('http://red.com/path/index.html');
url.href; // => 'http://red.com/path/index.html'
url.hostname = 'blue.io';
url.href; // => 'http://blue.io/path/index.html'

请注意,实例的onlyoriginsearchParamspropertiesURL()是只读的。所有其他的都是可写的,并在您更改它们时修改 URL。

9. 总结

URL()构造函数是很方便的解析(和验证)在JavaScript中的URL。

new URL(relativeOrAbsolute [, absoluteBase])接受绝对或相对 URL 作为第一个参数。当第一个参数是相对的时,您必须将第二个参数指示为绝对 URL,该 URL 为第一个参数的基础提供服务。

创建URL()实例后,您可以轻松访问最常见的 URL 组件,例如:

  • url.search 对于原始查询字符串
  • url.searchParams对于URLSearchParams选择查询字符串参数的实例
  • url.hostname 访问主机名
  • url.pathname 读取路径名
  • url.hash 确定哈希值

关于浏览器支持,URL构造函数在现代浏览器中可用。但是,它在 Internet Explorer 中不可用。

你最喜欢用什么工具来解析 JavaScript 中的 URL?

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

短暂又灿烂的

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值