字符串编码和解码,encodeURIComponent和decodeURIComponent用法

使用js内置函数进行编码解码

我们使用 JavaScript 中的 encodeURIComponent() 函数将 Unicode 字符串 unicodeString 编码为 UTF-8,并将结果存储在 utf8String 变量中。编码后的字符串将包含一些特殊字符和百分比编码。

然后,我们使用 decodeURIComponent() 函数对 utf8String 进行解码,将其还原为原始的 Unicode 字符串,并将结果存储在 decodedString 变量中。

示例:

// 编码(将 Unicode 字符串编码为 UTF-8)
var unicodeString = 'Hello, 你好';
var utf8String = encodeURIComponent(unicodeString);
console.log(utf8String); // 输出:Hello%2C%20%E4%BD%A0%E5%A5%BD

// 解码(将 UTF-8 编码还原为 Unicode 字符串)
var decodedString = decodeURIComponent(utf8String);
console.log(decodedString); // 输出:Hello, 你好

猜你喜欢

转载自blog.csdn.net/m0_47791238/article/details/132265902