JSON字符串转base64以及base64转urlsafeBASE64的方法(含小程序方法)

参考文章
https://blog.csdn.net/qq_43466457/article/details/103328931
https://blog.csdn.net/SeriousLose/article/details/110817689
https://blog.csdn.net/greatwang123/article/details/39104847

vue项目中JSON字符串可以直接通过window对象下挂的btoa()和atob()方法进行编码和解码

JSON转base64

//json转base64
var base64 = window.btoa(jsonCode)

base64转JSON

//base64转json
var jsonCode= window.atob(base64);

在小程序中并没有window对象 所以没有办法使用btoa和atob

json转base64

 base64_encode(str) {
        var c1, c2, c3;
        var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        var i = 0,
            len = str.length,
            string = '';

        while (i < len) {
            c1 = str.charCodeAt(i++) & 0xff;
            if (i == len) {
                string += base64EncodeChars.charAt(c1 >> 2);
                string += base64EncodeChars.charAt((c1 & 0x3) << 4);
                string += "==";
                break;
            }
            c2 = str.charCodeAt(i++);
            if (i == len) {
                string += base64EncodeChars.charAt(c1 >> 2);
                string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
                string += base64EncodeChars.charAt((c2 & 0xF) << 2);
                string += "=";
                break;
            }
            c3 = str.charCodeAt(i++);
            string += base64EncodeChars.charAt(c1 >> 2);
            string += base64EncodeChars.charAt(((c1 & 0x3) << 4) | ((c2 & 0xF0) >> 4));
            string += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >> 6));
            string += base64EncodeChars.charAt(c3 & 0x3F)
        }
        return string
    },

更新解码方法(MDN)

function base64ToJson(string){
let b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  let b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;
  string = String(string).replace(/[\t\n\f\r ]+/g, "");
  // console.log('string=========',string);
  if (!b64re.test(string))
    throw new TypeError("Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.");
  // Adding the padding if missing, for semplicity
  string += "==".slice(2 - (string.length & 3));
  let bitmap = "";
  let result = "";
  let r1 = "";
  let r2 = "";
  let i = 0;
  for (; i < string.length;) {
    bitmap = b64.indexOf(string.charAt(i++)) << 18 | b64.indexOf(string.charAt(i++)) << 12 |
      (r1 = b64.indexOf(string.charAt(i++))) << 6 | (r2 = b64.indexOf(string.charAt(i++)));

    result += r1 === 64 ? String.fromCharCode(bitmap >> 16 & 255) :
      r2 === 64 ? String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255) :
      String.fromCharCode(bitmap >> 16 & 255, bitmap >> 8 & 255, bitmap & 255);
  }
  return result;
}

MDN里的比较权威的方法,含解码方法(翻到下面的Polyfill)

https://developer.mozilla.org/zh-CN/docs/Web/API/WindowOrWorkerGlobalScope/btoa

什么是url_safe base64编码?

在base64传统编码中会出现+, /两个会被url直接转义的符号,
因此如果希望通过url传输这些编码字符串,
我们需要先做传base64编码,随后将+和/分别替换为- _两个字符,在接收端则做相反的动作解码

base64转urlsafeBASE64

 function urlSateBase64Encode(base64Str) {
    if (!base64Str) return;
    let safeStr = base64Str.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '’);
    // const UriSafe = (src: string) => src.replace(/[+\/]/g, (m0) => m0 == '+' ? '-' : '_').replace(/=+$/m, ‘');
    return safeStr
  }

urlsafeBASE64转base64

更新了一个错误 base64一定是4的倍数,不够补=

再次更新错误,有余数的时候再进行处理

function urlSafeBase64Decode(base64Str) {
    if (!base64Str) return;
    let safeStr = base64Str.replace(/-/g, '+').replace(/_/g, '/');
    let num = safeStr.length % 4; 
    // let num = 4 - safeStr.length % 4;
    if (num == 0) {

  	} else {
    	num = 4 - num
  	}
    return safeStr + '===='.substring(0, num);
  }

2021-6-8更新 含有中文的base64在解码后会有(中文)乱码的情况,解码后进行utf-8转utf-16的操作

utf-8转utf-16

function utf8ToUtf16(){
	//utf-8转utf-16
  let out, i, len, c;
  let char2, char3;
  out = "";
  len = str.length;
  i = 0;
  while (i < len) {
    c = str.charCodeAt(i++);
    switch (c >> 4) {
      case 0:
      case 1:
      case 2:
      case 3:
      case 4:
      case 5:
      case 6:
      case 7:
        // 0xxxxxxx
        out += str.charAt(i - 1);
        break;
      case 12:
      case 13:
        // 110x xxxx 10xx xxxx
        char2 = str.charCodeAt(i++);
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx 10xx xxxx 10xx xxxx
        char2 = str.charCodeAt(i++);
        char3 = str.charCodeAt(i++);
        out += String.fromCharCode(((c & 0x0F) << 12) |
          ((char2 & 0x3F) << 6) |
          ((char3 & 0x3F) << 0));
        break;
    }
  }
  return out;
}

utf-16转utf8

function(str) {
                let out, i, len, c;
                out = "";
                len = str.length;
                for(i = 0; i < len; i++) {
                    c = str.charCodeAt(i);
                    if ((c >= 0x0001) && (c <= 0x007F)) {
                        out += str.charAt(i);
                    } else if (c > 0x07FF) {
                        out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
                        out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
                        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                    } else {
                        out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
                        out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
                    }
                }
                return out;
            },

你可能感兴趣的:(js,base64,字符串,乱码)