在JavaScript中,可以使用内置的btoa()
函数来进行Base64编码。以下是一个示例代码:
const stringToEncode = "Hello, World!";
const encodedString = btoa(stringToEncode);
console.log(encodedString); // 输出:SGVsbG8sIFdvcmxkIQ==
const decodedString = atob(encodedString);
console.log(decodedString); // 输出:Hello, World!
在上面的代码中,我们首先定义了一个要编码的字符串stringToEncode
。然后,我们使用btoa()
函数将其进行Base64编码,结果存储在encodedString
变量中。通过打印encodedString
,我们可以看到编码后的字符串。
接下来,我们使用atob()
函数对编码后的字符串进行解码,结果存储在decodedString
变量中。通过打印decodedString
,我们可以看到解码后的字符串与原始字符串相同。
需要注意的是,btoa()
和atob()
函数只能用于ASCII字符。如果要编码的字符串包含非ASCII字符,我们可以使用encodeURIComponent()
函数将字符串转换为URI格式,然后再进行Base64编码。解码时,我们需要先使用atob()
函数解码Base64字符串,然后再使用decodeURIComponent()
函数将URI格式转换回原始字符串。示例如下:
const stringToEncode = "你好,世界!";
const encodedString = btoa(encodeURIComponent(stringToEncode));
console.log(encodedString); // 输出:JUU0JUJEJUEwJUU0JUI4JTkzJUU2JTlDJTg1JUU1JThCJUI2JUU2JTlEJTk4JUU1JTk3JUIzJUU4JUI0JUFEJUU1JThGJTgw
const decodedString = decodeURIComponent(atob(encodedString));
console.log(decodedString); // 输出:你好,世界!
在上面的代码中,我们首先定义了一个包含非ASCII字符的字符串stringToEncode
。然后,我们使用encodeURIComponent()
函数将字符串转换为URI格式,并将其传递给btoa()
函数进行Base64编码。编码后的字符串存储在encodedString
变量中。通过打印encodedString
,我们可以看到编码后的字符串。
接下来,我们使用atob()
函数解码Base64字符串,然后使用decodeURIComponent()
函数将URI格式转换回原始字符串。最后,通过打印decodedString
,我们可以看到解码后的字符串与原始字符串相同。
上一篇:Base64背景图片不显示