迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中的 URL 编码

作者:迹忆客 最近更新:2023/03/10 浏览次数:

URL 编码是在 URL 中用 % 后跟一个十六进制字符对 8 位字符进行编码的过程。它也被称为百分比编码,因为我们用百分号替换字符。URL 编码可以使用几乎任何编程语言完成,包括 JavaScript。

对 URL 进行编码的原因是 URL 只能包含 ASCII 表中的特定字符。URL 中存在的所有其他字符都需要进行编码才能使 URL 正常工作。URL 中需要编码的字符有':''/''?''#''['']''@''!''$', '&', "'", '(', ')', '*', '+'','';''=', 以及 '%'。有关这些字符及其编码形式的更多信息,你可以访问此链接

在继续之前,让我们先了解一下 URI 和 URL。

统一资源标识符 (URI) 用于标识 Internet 上的资源。相比之下,统一资源定位器 (URL) 可以帮助你定位和访问该资源。

URI 既可以是标识符也可以是定位器,而 URL 只能是定位器。URL 位于 URI 下;因此,它们听起来有点相似,但它们之间有细微的差别。

例如,facebook.com 是一个 URL,因为它获取 Facebook 网页所在的位置,而附近的咖啡店可以是 URI,因为你知道咖啡店(这是一种资源)的位置,并且你也知道如何获取那里(路径)。

encodeURI() 方法是可用于在 JavaScript 中对 URL 进行编码的方法之一。如果你有完整的 URL,则可以使用此方法。

假设我们有一个 URL 为 https://en.wikipedia.org/[$q=english &language],现在让我们使用 encodeURI() 方法对这个 URL 进行编码,看看这个方法提供了什么输出。

const URL = "https://en.wikipedia.org/[$q=english &language]";
console.log(encodeURI(URL));

输出:

https://en.wikipedia.org/%5Bq=english%20&language%5D

请注意,此方法仅对 URL 中的少数字符(如空格和方括号)进行编码。

此方法不会对以下特殊字符进行编码。

encodeURI()` will not encode: `~!@#$&*()=:/,;?+'

如果要对其他一些特殊字符进行编码,可以使用 encodeURIComponent() 方法。

encodeURIComponent() 方法也可用于对 URL 进行编码。如果你只有 URL 的一部分,则可以使用此方法。正如我们已经看到的,encodeURI() 方法编码的字符非常少,但是如果你也想编码其他一些字符,你可以使用 encodeURIComponent() 方法。

让我们采用之前采用的相同 URL,看看当我们使用这种方法对字符串进行编码时,我们得到了什么输出。

const URL = "https://en.wikipedia.org/[$q=english &language]";
console.log(encodeURIComponent(URL));

输出:

https%3A%2F%2Fen.wikipedia.org%2F%5B%24q%3Denglish%20%26language%5D

如你所见,此方法已对大部分 URL 进行了编码。

此方法不会对以下特殊字符进行编码。

encodeURIComponent()` will not encode: `~!*()'

根据你的要求和使用情况,你可以使用上述两种方法中的一种或两种在 JavaScript 中对 URL 进行编码。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

用 jQuery 检查复选框是否被选中

发布时间:2024/03/24 浏览次数:102 分类:JavaScript

在本教程中学习 jQuery 检查复选框是否被选中的所有很酷的方法。我们展示了使用直接 DOM 操作、提取 JavaScript 属性的 jQuery 方法以及使用 jQuery 选择器的不同方法。你还将找到许多有用的

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便