如何使用 JavaScript 函数编码 URL?


众所周知,URL 是一个网址。什么是 URL 编码,为什么我们需要对URL进行编码?将字符串转换为准确的 URL 格式的过程称为 URL 编码。

有效的 URL 格式仅使用“字母 | 数字 | 安全 | 附加 | 转义”字符。URL 中只允许使用有限的标准128 个 ASCII字符。需要加密不属于此集合的保留字符。URL 编码提高了 URL 的可靠性和安全性。

每个需要 URL 编码的字符都使用字符“%”和与其 utf-8 字符对应的两位十六进制值进行编码。

例如,

¥€¢£¥€¢£^°√•
will be encoded to
C2%A5%E2%82%AC%C2%A2%C2%A3%C2%A5%E2%82%AC%C2%A2%C2%A3%5E%C2%B0%E2%88%9A%E
2%80%A2

使用 encodeURI() 方法

在本节中,让我们检查 encodeURI() 方法以在 JavaScript 中编码 URL。encodeURI() 是编码 URL 的通用方法。唯一的缺点是此方法不编码字符~!@#$&*()=:/,;?+ 在这种情况下,我们采用另一种方法。

语法

请按照以下语法使用此方法。

encodeURI(uri)

在 encodeURI() 的语法中,我们需要发送一个参数,该参数将是要编码的 URL 或字符串。

算法

  • 步骤 1 - 定义一个执行编码的函数。

  • 步骤 2 - 根据编码的需要,将 URL 字符串作为参数传递给函数。也就是说,根据方法的编码能力。

  • 步骤 3 - 显示输出。

示例

在此示例中,我们使用一个函数来执行 encodeURI()。正如我们上面学到的那样,我们根据方法的工作方式传递了 URL 字符串。

<html> <body> <h2>Using the <i>encodeURI()</i> method.</h2> <p id="idEnOutput"></p> <script> function doEncode(str) { var encode, dispEl, disStr = "encodeURI"; dispEl = document.getElementById("idEnOutput"); encode = encodeURI(str); dispEl.innerHTML = disStr + "<br>" + encode; } doEncode("https://tutorialspoint.com/check doc?qp=abc and xyz&count=1"); </script> </body> </html>

使用 encodeURIComponent() 方法

在本节中,让我们检查encodeURIComponent() 方法以在 JavaScript 中编码 URL。encodeURI() 是编码 URL 的通用方法。

并且诸如 / ? : @ & = + $ * # 和类似字符不会被 encodeURI() 方法编码。作为替代方法,使用 encodeURIComponent() 函数。但是,诸如 A-Z a-z 0-9 - _.! ~ * ' () 等字符不会被 encodeURIComponent 方法编码。

语法

encodeURIComponent(uri)

encodeURIComponent() 的语法中,我们需要发送一个参数,该参数将是要编码的 url 或字符串。

示例

在此示例中,我们使用一个函数来执行encodeURIComponent()。正如我们上面学到的那样,我们根据方法的工作方式传递了 URL 字符串。

<html> <body> <h2>Using the <i>encodeURIComponent()</i> method.</h2> <p id="idEnOutput"></p> <script> function doEncode(str) { var encode, dispEl, disStr = "encodeURIComponent"; dispEl = document.getElementById("idEnOutput"); encode = encodeURIComponent(str); dispEl.innerHTML = disStr + "<br>" + encode; } doEncode("qstr?qtxt=me@gmail.com"); </script> </body> </html>

在本教程中,我们看到了在 JavaScript 中编码 URL 的两种方法。

与 encodeURIComponent() 方法相比,encodeURI() 方法更好。因为 encodeURIComponent() 会对整个 URL 以及域名进行编码。这会产生无效的 URL。因此,只有当我们需要编码 encodeURI() 方法不会编码的字符时,才能使用此方法。

更新于:2022年8月23日

2K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.