在 JavaScript 中将字符串编码和解码为 Base64
Base64 编码字符集由 A-Z
、a-z
、0-9
、+
和 /
组成。该系统总共有 64 个字符,因此称为 Base64。Base64 编码将数据转换为 ASCII(美国信息交换标准代码)格式。
例如,如果你有一个字符串 Git,那么在 Base64 编码格式中,该字符串将表示为 R29vZ2xl
。
这里刚刚发生的是,字符串的各个字符首先被表示为它们的 ASCII 值,即对于大写的 G
,其 ASCII 值是 71
,对于小的 i
,其 ASCII 值是 105
,并且其他角色也类似。要获取 ASCII 值的完整列表,请访问此链接。
然后将这些 ASCII 值转换为 8 位二进制表示。这个 8 位二进制表示然后被分成四个 6 位段。然后将这四个二进制段转换为十进制。
最后,这些十进制数字被按照 Base64 编码表转换为 Base64。
现在我们不必手动完成所有这些转换。到目前为止,我们所看到的只是为了理解目的。让我们看看如何将字符串编码和解码为 Base64。
在 JavaScript 中,我们有两个 Base64 辅助函数,btoa()
和 atob()
,用于将字符串转换为 Base64 编码,反之亦然。btoa()
接受一个字符串并将其编码为 Base64,而 atob()
接受一个编码字符串并对其进行解码。
在下面的代码中,我们有两个 div
元素,我们将在其中显示编码和解码的字符串。我们使用 JavaScript 中的 getElementById()
方法将这两个 div
的引用存储在 myDiv_1
和 myDiv_2
中。我们将在本例中编码和解码的字符串是存储在 str
变量中的 Git。
为了编码这个字符串,我们将使用 btoa()
函数。为此,只需将 str
变量作为参数传递给该函数。我们将把这个结果存储在 encodedStr
变量中。然后我们将使用 myDiv_1.innerHTML
属性在 div_1
中显示此变量的值。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<div id="div_1"></div>
<div id="div_2"></div>
<script>
let myDiv_1 = document.getElementById('div_1');
let myDiv_2 = document.getElementById('div_2');
let str = "Git";
let encodedStr = btoa(str);
myDiv_1.innerHTML = encodedStr;
</script>
</body>
</html>
输出:
R2l0
这就是你将获得的输出。该字符串未转换为 Base64。
现在要将上述字符串解码为原始形式,你可以使用 atob()
函数并在其中传递 encodedStr
。然后使用 myDiv_2.innerHTML
属性在 div_2
中显示 decodedStr
变量的值。
let decodedStr = atob(encodedStr);
myDiv_2.innerHTML = decodedStr;
输出:
Git
请注意,Base64 用于发送二进制数据,而不是一种加密方法。此外,它不是一种压缩方法。
相关文章
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 选择器的不同方法。你还将找到许多有用的
jQuery 中的 Window.onload 与 $(document).ready
发布时间:2024/03/24 浏览次数:180 分类:JavaScript
-
本教程演示了如何在 jQuery 中使用 Window.onload 和 $(document).ready 事件。