微信小程序字符串含中文转base64,与base64回显中文
时间: 2023-11-17 19:19:08 浏览: 357
在微信小程序中,字符串含中文转base64可以使用以下代码实现:
```javascript
// 将字符串转成UTF-8编码的ArrayBuffer
function str2ab(str) {
let buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
let bufView = new Uint16Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
// 将ArrayBuffer转成base64字符串
function ab2base64(arrayBuffer) {
let base64 = wx.arrayBufferToBase64(arrayBuffer);
return base64;
}
// 示例
let str = "你好,世界!";
let arrayBuffer = str2ab(str);
let base64 = ab2base64(arrayBuffer);
console.log(base64); // 5L2g5aW977yM5LiW55WM77yB
```
要注意,在字符串含有中文等非ASCII字符时,必须将字符串转成UTF-8编码的ArrayBuffer,否则会出现乱码。
而base64回显中文,则需要将base64字符串转回原始字符串,方法如下:
```javascript
// 将base64字符串转成ArrayBuffer
function base642ab(base64) {
let arrayBuffer = wx.base64ToArrayBuffer(base64);
return arrayBuffer;
}
// 将ArrayBuffer转成字符串
function ab2str(arrayBuffer) {
let decoder = new TextDecoder("utf-8");
let str = decoder.decode(arrayBuffer);
return str;
}
// 示例
let base64 = "5L2g5aW977yM5LiW55WM77yB";
let arrayBuffer = base642ab(base64);
let str = ab2str(arrayBuffer);
console.log(str); // 你好,世界!
```
同样需要注意,在base64字符串含有中文等非ASCII字符时,必须将base64字符串转成UTF-8编码的ArrayBuffer。
阅读全文