如何在 JavaScript 中编码字符串?
在这篇文章中,我们将学习如何使用合适的示例在 JavaScript 中编码字符串。
编码是从一种数据格式转换为另一种数据格式的过程。在计算机科学术语中,编码是将文本转换为密文的过程。编码与加密过程不同。
编码和加密的区别在于,编码用于保持数据可用性,而加密用于维护数据机密性。编码不使用密钥进行编码过程,而加密需要密钥进行加密过程。在 JavaScript 中用于编码字符串的方法有 btoa()、encodeURI() 和 encodeURIComponent()。
使用 btoa() 方法
使用 btoa() 函数,将字符串以 base-64 编码转换为 Base64 编码的 ASCII 字符串。btoa() 方法的语法如下:
btoa(string);
其中,参数 **string** 是要编码的字符串。返回值是编码后的字符串。
示例 1
这是一个使用 **btoa()** 方法编码字符串的示例程序。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Encoding a string in JavaScript.</title>
</head>
<body>
<p id="encode"></p>
<script>
var str = "Tutorials point";
document.getElementById('encode').innerHTML = 'The encoded string for "Tutorials point" is '+window.btoa(str);
</script>
</body>
</html>
上述示例程序的输出为:
使用 encodeURI() 方法
**encodeURI()** 函数通过将某些字符(如空格)替换为表示字符 UTF-8 编码的转义序列来编码 URI 或字符串。**encodeURI()** 方法的语法如下:
encodeURI(uri);
其中,参数 **uri** 是完整的 URI 或字符串。返回值是编码后的字符串。
示例 2
这是一个使用 **encodeURI()** 方法编码字符串的示例程序。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Encoding a string in JavaScript.</title>
</head>
<body>
<p id="encode"></p>
<script>
var str1 = "Tutorials point";
var uri = "https://twitter.com/Google?ref_src=twsrc%5Egoogle";
document.getElementById('encode').innerHTML = 'The encoded string for "Tutorials point" is '+encodeURI(str1)+'<br/>'+'The encoded string for "https://twitter.com/Google?ref_src=twsrc%5Egoogle" is '+encodeURI(uri);
</script>
</body>
</html>
上述示例程序的输出为:
使用 encodeURIComponent() 方法
**encodeURIComponent()** 方法是 encodeURI() 方法的增强版本。**encodeURI()** 和 **encodeURIComponent()** 方法的区别在于:使用 **encodeURI()** 编码整个 URL,而使用 **encodeURIComponent()** 编码 URI 组件(如查询字符串)。**encodeURIComponent()** 可以编码 (‘#’,’&’,’$’,’/’,’:’,’;’,’@’,’?’) 等 **encodeURI()** 方法无法编码的字符。**encodeURIComponent()** 方法的语法如下:
encodeURIComponent(value);
其中,**value** 可以是布尔值、字符串,数字会在编码前转换为字符串。返回值是编码后的字符串。
示例 3
这是一个使用 **encodeURIComponent()** 方法编码字符串的示例程序。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Encoding a string in JavaScript.</title>
</head>
<body>
<p id="encode"></p>
<script>
var str1 = "Tutorials point";
var uriComp = "https://twitter.com/Google?ref_src=twsrc%5Egoogle";
document.getElementById('encode').innerHTML = 'The encoded string for "Tutorials point" is '+encodeURIComponent(str1)+'<br/>'+'The encoded string for "https://twitter.com/Google?ref_src=twsrc%5Egoogle" is '+encodeURIComponent(uriComp);
</script>
</body>
</html>
上述示例程序的输出为:
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP