js进行utf-8与base64的编码和解码,并避免出现乱码情况

1,621 阅读1分钟

​ 在携带参数访问网络地址时,而服务器在接受参数时,一些中文utf-8要转成base64编码格式才能接收成功,不然会报错,转码方法如下:

//utf-8 转 base64
const txt = new Buffer('文字').toString('base64');
console.log(txt)
 
//base64 转 utf-8
const ztxt = new Buffer(txt, 'base64').toString('utf8');
console.log(ztxt)

注意在编码后,可能会有一些特殊的字符,所以还需将编码再进行一次编码过滤,可以利用encodeURIComponent()方法和decodeURIComponent()方法,保证特殊字符不会被服务器单独解析报错,解析后也不会乱码,方法如下:

const txt = new Buffer('文字').toString('base64');
//encodeURIComponent() 函数可以把字符串作为 URI 组件进行编码并且不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码
const urltxt = encodeURIComponent(txt);
console.log(urltxt)
 
//所对应的,在需要将base64转为utf-8,须提前用decodeURIComponent()进行一次解码,才可以保证解码成功,不乱码
//decodeURIComponent()函数可对 encodeURIComponent() 函数编码的 URI 进行解码。
const zurltxt = new Buffer(decodeURIComponent(urltxt), 'base64').toString('utf8');
console.log(zurltxt)

欢迎交流! ​