浅谈JavaScript中你可能不知道URL构造函数的属性

作者:vipbic 时间:2024-04-17 10:03:03 

URL

URL 是统一资源定位符,对可以从互联网上得到的资源的位置和访问方法的一种简洁的表示,是互联网上标准资源的地址。互联网上的每个文件都有一个唯一的 URL,它包含的信息指出文件的位置以及浏览器应该怎么处理它,

在 Web 开发中,有许多情况需要解析 URL,这篇主要学习如何使用 URL 对象实现这一点

例如,这里是这篇博客文章的路径:

https://www.vipbic.com/thread.html?id=101

通常您需要访问 URL 的特定属性。这些可能是主机名(例如 vipbic.com ) ,或者路径名(例如/thread)

JavaScript用于访问URL对象的提供一个URL()构造函数,很方便解析

一个完整URL

用一张图片来解释,没有太多的文字描述,在下面的图片中你可以找到一个 URL 的主要包含属性:

浅谈JavaScript中你可能不知道URL构造函数的属性

URL constructor

URL ()是一个 constuctor 函数,它可以解析 URL 的对象:


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

relativeOrAbsolute参数可以是绝对 URL,也可以是相对 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'

创建 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;
}

可以尝试在浏览中打印

浅谈JavaScript中你可能不知道URL构造函数的属性

Query string

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; // => ''

Parsing query string

浅谈JavaScript中你可能不知道URL构造函数的属性

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

一种简单的查询参数选择方法提供了 url.searchParams 属性,该属性包含 URLSearchParams 的实例

URLSearchParams 对象提供了许多方法(如 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

get.('message'),返回消息查询参数的值-‘ hello',当去尝试,访问一个不存在的参数 url.searchParams.get('missing')的结果为 null

hostname

Hostname 属性包含 URL 的主机名:


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

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; // => '/'

hash

可以使用 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; // => ''

URL validation

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

例如,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

URL manipulation

除了访问 URL 属性之外,搜索、主机名、路径名、hash等属性都是可写的ーー因此您可以操作 URL

例如,让我们把现有 URL 的主机名从 red. com 修改为 blue.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'

注意,只有 URL ()实例的 originsearchParams 属性是只读的。其他的都是可写的,当你改变它们的时候可以修改 URL

总结

URL()构造函数可以方便地在 JavaScript 中解析(和验证) URL

new URL (relativeOrAbsolute [ ,absolute base ])接受作为第一个参数的绝对或相对 URL。如果第一个参数是相对的,则必须将第二个参数指

示为一个作为第一个参数基础的URL

创建 URL()实例后,可以获取到以下实列方法

  • url.search 原始查询字符串

  • url.searchParams 选择查询字符串参数

  • url.hostname 访问主机名

  • url.pathname 读取路径名

  • url.hash #后面的参数

文章属于翻译,作者部分有所改动,

作者:羊先生

英文原文, https://dmitripavlutin.com/parse-url-javascript/

来源:https://segmentfault.com/a/1190000023189741

标签:JavaScript,URL,构造函数
0
投稿

猜你喜欢

  • 浅谈对Python变量的一些认识理解

    2021-06-10 05:06:52
  • 二级联动下拉菜单javascript源码

    2010-03-16 12:32:00
  • CentOS 6.4下编译安装MySQL5.6.14教程

    2024-01-20 01:06:43
  • ajax+asp无限级分类树型结构

    2011-04-02 11:05:00
  • JavaScript使用math.js进行精确计算操作示例

    2024-04-10 10:54:41
  • 前端来看看 maxthon bugs

    2008-09-23 18:35:00
  • Tensorflow矩阵运算实例(矩阵相乘,点乘,行/列累加)

    2023-12-19 04:07:42
  • python实现opencv+scoket网络实时图传

    2023-07-03 16:09:17
  • Laravel框架实现定时发布任务的方法

    2023-11-22 23:54:57
  • windows下Virtualenvwrapper安装教程

    2023-11-08 02:15:20
  • python快速排序的实现及运行时间比较

    2022-11-30 20:41:27
  • 基于Python实现拉格朗日插值法

    2022-03-18 18:52:18
  • 详解Mysql基础语法的使用

    2024-01-28 07:50:05
  • python获取文件路径、文件名、后缀名的实例

    2022-05-05 10:47:27
  • jQuery实现的简单分页示例

    2024-04-09 19:45:29
  • Python使用xpath实现图片爬取

    2023-07-10 16:45:42
  • 浅谈python已知元素,获取元素索引(numpy,pandas)

    2023-08-04 16:01:00
  • vue中beforeRouteLeave实现页面回退不刷新的示例代码

    2024-05-09 15:11:16
  • Go语言中使用flag包对命令行进行参数解析的方法

    2024-02-15 00:45:09
  • Python requests库用法实例详解

    2021-03-31 19:36:30
  • asp之家 网络编程 m.aspxhome.com