Skip to content

Commit

Permalink
feat(parse-url)
Browse files Browse the repository at this point in the history
  • Loading branch information
lv-z-l committed Sep 13, 2023
1 parent ab408fa commit a012292
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
41 changes: 41 additions & 0 deletions articles/js/deep/escape-encodeuri.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
---
title: escape、encodeURI、encodeURIComponent的区别
author: lvzl
---

`escape()`, `encodeURI()`, 和 `encodeURIComponent()` 都是用于在 JavaScript 中处理字符串的方法,但它们的作用和用法有一些不同。

1. `escape()`
- `escape()` 方法用于对字符串进行编码,将非 ASCII 字符和某些特殊字符转换为 `%` 后跟两位十六进制表示的字符。
- 该方法已被废弃,不推荐使用,因为它不会对所有字符进行正确编码,而且在处理 URI 和 URL 时存在问题。通常,应该使用 `encodeURI()``encodeURIComponent()` 来代替。

```javascript
var originalString = "你好,world!";
var encodedString = escape(originalString);
console.log(encodedString); // "%u4F60%u597D%uFF0Cworld%21"
```

2. `encodeURI()`
- `encodeURI()` 方法用于对整个 URI 进行编码,它将字符串中的特殊字符进行编码,但保留某些字符(例如 `/`, `:`, `?`, `&`, `=`)不编码,以便构建有效的 URI。
- 这个方法通常用于编码整个 URI,而不是单独的参数值。

```javascript
var uri = "https://www.example.com/search?query=你好";
var encodedURI = encodeURI(uri);
console.log(encodedURI); // "https://www.example.com/search?query=%E4%BD%A0%E5%A5%BD"
```

3. `encodeURIComponent()`
- `encodeURIComponent()` 方法用于对 URI 组件中的特殊字符进行编码,包括 `/`, `:`, `?`, `&`, `=`, 空格等。这个方法通常用于编码单独的参数值,以确保参数值不会破坏 URI 的结构。

```javascript
var paramValue = "你哈:?&/=";
var encodedParamValue = encodeURIComponent(paramValue);
console.log(encodedParamValue); // '%E4%BD%A0%E5%93%88%3A%3F%26%2F%3D'
```

总结:

- `escape()` 已被废弃,不应再使用。
- `encodeURI()` 用于编码整个 URI,通常用于整个 URL 的编码,保留某些字符(例如 `/`, `:`, `?`, `&`, `=`)不编码。
- `encodeURIComponent()` 用于编码 URI 组件中的特殊字符,通常用于单独的参数值的编码。
37 changes: 37 additions & 0 deletions articles/write/parse-url.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
---
title: 解析URL
author: lvzl
---

```js
// 要解析的URL
var urlString = "https://www.example.com:8080/path/to/resource?param1=value1&param2=value2#section3";

// 创建一个URL对象
var url = new URL(urlString);

// 获取各个部分
var protocol = url.protocol; // 协议(包括冒号):https:
var host = url.host; // 主机名(包括端口号):www.example.com:8080
var hostname = url.hostname; // 主机名:www.example.com
var port = url.port; // 端口号:8080
var pathname = url.pathname; // 路径:/path/to/resource
var search = url.search; // 查询参数(包括问号):?param1=value1&param2=value2
var hash = url.hash; // 片段标识符(包括井号):#section3
var searchParams = url.searchParams; // 查询参数的键值对对象

// 输出各个部分
console.log("协议: " + protocol);
console.log("主机名: " + host);
console.log("主机名 (不包括端口号): " + hostname);
console.log("端口号: " + port);
console.log("路径: " + pathname);
console.log("查询参数: " + search);
console.log("片段标识符: " + hash);

// 输出查询参数的键值对
searchParams.forEach(function(value, key) {
console.log("查询参数 " + key + ": " + value);
});

```

0 comments on commit a012292

Please sign in to comment.