在 JavaScript 中,可以使用 btoa()
函数将字符串进行 Base64 编码。以下是一个示例:
let str = "Hello, world!";
let encoded = btoa(str);
console.log(encoded); // "SGVsbG8sIHdvcmxkIQ=="
在这个例子中,我们先定义一个字符串 str
,它包含了 "Hello, world!"。然后,我们使用 btoa()
函数对该字符串进行 Base64 编码,并将结果存储在变量 encoded
中。最后,我们使用 console.log()
函数将编码后的字符串打印出来。
需要注意的是,btoa()
函数仅适用于 ASCII 字符串。如果要编码的字符串包含非 ASCII 字符,需要先进行转换。例如:
let str = "你好,世界!";
let encoded = btoa(unescape(encodeURIComponent(str)));
console.log(encoded); // "5L2g5aW977yM5LiW55WMhJWQkA=="
在这个例子中,我们的字符串包含中文字符,因此需要使用 encodeURIComponent()
函数将其转换为 URI 格式的字符串,然后使用 unescape()
函数将其转换回原始字符串。最后,我们使用 btoa()
函数对该字符串进行 Base64 编码,并将结果存储在变量 encoded
中。