最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

關(guān)于base64編碼和解碼的js工具函數(shù)

 更新時(shí)間:2023年02月08日 09:38:47   作者:weixin_44953227  
這篇文章主要介紹了關(guān)于base64編碼和解碼的js工具函數(shù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

base64編碼和解碼的js工具函數(shù)

上代碼

// 使用
const base64 = new Base64Code()
const str = '你好'
const en = base64.enCode(str)
const de = base64.deCode(en)
console.log(en, 'base64編碼') // 5L2g5aW9
console.log(de, 'base64解碼') // 你好

|| 中文也可以進(jìn)行編碼, 里面已經(jīng)對(duì)數(shù)據(jù)UTF-8轉(zhuǎn)碼再base64編碼

// base64函數(shù)
function Base64Code() {
    // base64 character set, plus padding character (=)
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

        // Regular expression to check formal correctness of base64 encoded strings
        b64re = /^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/;

    // 轉(zhuǎn)UTF-8格式編碼 private method for UTF-8 encoding
    const utf8Encode = function (str) {
        let string = str;
        string = string.replace(/\r\n/g, '\n');
        let utfText = '';
        for (let n = 0; n < string.length; n++) {
        const c = string.charCodeAt(n);
        if (c < 128) {
            utfText += String.fromCharCode(c);
        } else if ((c > 127) && (c < 2048)) {
            utfText += String.fromCharCode((c >> 6) | 192);
            utfText += String.fromCharCode((c & 63) | 128);
        } else {
            utfText += String.fromCharCode((c >> 12) | 224);
            utfText += String.fromCharCode(((c >> 6) & 63) | 128);
            utfText += String.fromCharCode((c & 63) | 128);
        }

        }
        return utfText;
    };

    // 解UTF-8格式編碼 private method for UTF-8 decoding
    const utf8Decode = function (utfText) {
        let string = '';
        let i = 0;
        let c = 0;
        let c2 = 0;
        let c3 = 0;
        while (i < utfText.length) {
        c = utfText.charCodeAt(i);
        if (c < 128) {
            string += String.fromCharCode(c);
            i++;
        } else if ((c > 191) && (c < 224)) {
            c2 = utfText.charCodeAt(i + 1);
            string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = utfText.charCodeAt(i + 1);
            c3 = utfText.charCodeAt(i + 2);
            string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
        }
        return string;
    };
    
    // base64編碼
    this.enCode = function(string) {
        string = utf8Encode(String(string));
        var bitmap, a, b, c,
            result = "",
            i = 0,
            rest = string.length % 3; // To determine the final padding

        for (; i < string.length;) {
            if ((a = string.charCodeAt(i++)) > 255 ||
                (b = string.charCodeAt(i++)) > 255 ||
                (c = string.charCodeAt(i++)) > 255)
                throw new TypeError("Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.");

            bitmap = (a << 16) | (b << 8) | c;
            result += b64.charAt(bitmap >> 18 & 63) + b64.charAt(bitmap >> 12 & 63) +
                b64.charAt(bitmap >> 6 & 63) + b64.charAt(bitmap & 63);
        }

        // If there's need of padding, replace the last 'A's with equal signs
        return rest ? result.slice(0, rest - 3) + "===".substring(rest) : result;
    };

    // base64解碼
    this.deCode = function(string) {
        // atob can work with strings with whitespaces, even inside the encoded part,
        // but only \t, \n, \f, \r and ' ', which can be stripped.
        string = String(string).replace(/[\t\n\f\r ]+/g, "");
        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));
        var bitmap, result = "",
            r1, r2, 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 utf8Decode(result);
    };
}

前端實(shí)現(xiàn)base64解碼編碼

本文描述了三種前端實(shí)現(xiàn)base64解碼和編碼的方法

Base64 在線編碼解碼工具 https://base64.us/

方法一:btoa 和 atob

btoa 和 atob 是window對(duì)象上的兩個(gè)函數(shù),window.atob()解碼window.btoa()編碼

let encodeText = 'xiaxiayaoguai'
let decodeText = 'eGlheGlheWFvZ3VhaQ=='
console.log(atob(decodeText)) // xiaxiayaoguai
console.log(btoa(encodeText)) // eGlheGlheWFvZ3VhaQ==

Unicode字符編碼報(bào)錯(cuò)

這里我們將encodeText = '霞霞要乖'再進(jìn)行解碼就會(huì)出現(xiàn)以下報(bào)錯(cuò),因?yàn)閎toa不支持Unicode字符編碼

Failed to execute ‘btoa’ on ‘Window’: The string to be encoded contains characters outside of the Latin1 range.

報(bào)錯(cuò)解決辦法:

  • 編碼時(shí),先用encodeURIComponent對(duì)字符串進(jìn)行編,再用btoa進(jìn)行Base64編碼;
  • 解碼時(shí),先用atob對(duì)Base64編碼的串進(jìn)行解碼,再用decodeURIComponent對(duì)字符串進(jìn)行解碼
let encodeText = '霞霞要乖'
let decodeText = 'JUU5JTlDJTlFJUU5JTlDJTlFJUU4JUE2JTgxJUU0JUI5JTk2'
console.log(btoa(encodeURIComponent(encodeText))) // JUU5JTlDJTlFJUU5JTlDJTlFJUU4JUE2JTgxJUU0JUI5JTk2
console.log(decodeURIComponent(atob(decodeText))) // 霞霞要乖

方法二:下包

下包

npm install --save js-base64

使用

<script>
    import {Base64} from 'js-base64' // 引入
    export default {
      data() {
        return {
          encodeText:'霞霞要乖',
          decodeText:'6Zye6Zye6KaB5LmW',
        }
      },
      created(){
        this.transformBase64()
      },
      methods: {
        transformBase64(){
          console.log('編碼:', Base64.encode(this.encodeText)) // 6Zye6Zye6KaB5LmW
          console.log('解碼:', Base64.decode(this.decodeText)) // 霞霞要乖
        }
      }
}
</script>

方法三:js實(shí)現(xiàn)

構(gòu)建函數(shù)

let Base64 = {
    keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    encode: function(e) {
      let t = "";
      let n, r, i, s, o, u, a;
      let f = 0;
      e = Base64._utf8_encode(e);
      while (f < e.length) {
        n = e.charCodeAt(f++);
        r = e.charCodeAt(f++);
        i = e.charCodeAt(f++);
        s = n >> 2;
        o = (n & 3) << 4 | r >> 4;
        u = (r & 15) << 2 | i >> 6;
        a = i & 63;
        if (isNaN(r)) {
          u = a = 64
        } else if (isNaN(i)) {
          a = 64
        }
        t = t + this.keyStr.charAt(s) + this.keyStr.charAt(o) + this.keyStr.charAt(u) + this.keyStr.charAt(a)
      }
      return t
    },

    decode: function(e) {
      let t = "";
      let n, r, i;
      let s, o, u, a;
      let f = 0;
      e = e.replace(/[^A-Za-z0-9+/=]/g, "");
      while (f < e.length) {
        s = this.keyStr.indexOf(e.charAt(f++));
        o = this.keyStr.indexOf(e.charAt(f++));
        u = this.keyStr.indexOf(e.charAt(f++));
        a = this.keyStr.indexOf(e.charAt(f++));
        n = s << 2 | o >> 4;
        r = (o & 15) << 4 | u >> 2;
        i = (u & 3) << 6 | a;
        t = t + String.fromCharCode(n);
        if (u != 64) {
          t = t + String.fromCharCode(r)
        }
        if (a != 64) {
          t = t + String.fromCharCode(i)
        }
      }
      t = Base64._utf8_decode(t);
      return t
    },

    _utf8_encode: function(e) {
      e = e.replace(/rn/g, "n");
      let t = "";
      for (let n = 0; n < e.length; n++) {
        let r = e.charCodeAt(n);
        if (r < 128) {
          t += String.fromCharCode(r)
        } else if (r > 127 && r < 2048) {
          t += String.fromCharCode(r >> 6 | 192);
          t += String.fromCharCode(r & 63 | 128)
        } else {
          t += String.fromCharCode(r >> 12 | 224);
          t += String.fromCharCode(r >> 6 & 63 | 128);
          t += String.fromCharCode(r & 63 | 128)
        }
      }
      return t
    },

    _utf8_decode: function(e) {
      let t = "";
      let n = 0;
      let r = c1 = c2 = 0;
      while (n < e.length) {
        r = e.charCodeAt(n);
        if (r < 128) {
          t += String.fromCharCode(r);
          n++
        } else if (r > 191 && r < 224) {
          c2 = e.charCodeAt(n + 1);
          t += String.fromCharCode((r & 31) << 6 | c2 & 63);
          n += 2
        } else {
          c2 = e.charCodeAt(n + 1);
          c3 = e.charCodeAt(n + 2);
          t += String.fromCharCode((r & 15) << 12 | (c2 & 63) << 6 | c3 & 63);
          n += 3
        }
      }
      return t
    }
  }

使用

let encodeText = '霞霞要乖'
let decodeText = '6Zye6Zye6KaB5LmW'
console.log(Base64.encode(encodeText)) // 6Zye6Zye6KaB5LmW
console.log(Base64.decode(decodeText)) // 霞霞要乖

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • 完美解決IE9瀏覽器出現(xiàn)的對(duì)象未定義問(wèn)題

    完美解決IE9瀏覽器出現(xiàn)的對(duì)象未定義問(wèn)題

    下面小編就為大家?guī)?lái)一篇完美解決IE9瀏覽器出現(xiàn)的對(duì)象未定義問(wèn)題。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧,祝大家游戲愉快哦
    2016-09-09
  • JavaScript 性能提升之路(推薦)

    JavaScript 性能提升之路(推薦)

    這篇文章主要介紹了JavaScript性能提升,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • javascript 如何生成不重復(fù)的隨機(jī)數(shù)

    javascript 如何生成不重復(fù)的隨機(jī)數(shù)

    javascript 如何生成不重復(fù)的隨機(jī)數(shù)...
    2007-11-11
  • 頁(yè)面版文本框智能提示JS代碼

    頁(yè)面版文本框智能提示JS代碼

    首先說(shuō)下背景,該code用于一個(gè)多條件查詢(xún)界面,原本該查詢(xún)條件由一個(gè)下拉列表提供,但是由于下拉列表數(shù)據(jù)量過(guò)大,用戶(hù)使用不方便,便希望在頁(yè)面給出一個(gè)智能提示的功能,但搜索的數(shù)據(jù)來(lái)自下拉列表
    2009-11-11
  • JS實(shí)現(xiàn)將人民幣金額轉(zhuǎn)換為大寫(xiě)的示例代碼

    JS實(shí)現(xiàn)將人民幣金額轉(zhuǎn)換為大寫(xiě)的示例代碼

    本篇文章主要是對(duì)使用JS實(shí)現(xiàn)將人民幣金額轉(zhuǎn)換為大寫(xiě)的示例代碼進(jìn)行了介紹,需要的朋友可以過(guò)來(lái)參考下,希望對(duì)大家有所幫助
    2014-02-02
  • JavaScript中的this/call/apply/bind的使用及區(qū)別

    JavaScript中的this/call/apply/bind的使用及區(qū)別

    這篇文章主要介紹了JavaScript中的this/call/apply/bind的使用及區(qū)別,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-03-03
  • js自調(diào)用匿名函數(shù)的三種寫(xiě)法(推薦)

    js自調(diào)用匿名函數(shù)的三種寫(xiě)法(推薦)

    下面小編就為大家?guī)?lái)一篇js自調(diào)用匿名函數(shù)的三種寫(xiě)法(推薦)。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2016-08-08
  • JavaScript 對(duì)象模型 執(zhí)行模型

    JavaScript 對(duì)象模型 執(zhí)行模型

    簡(jiǎn)單數(shù)值類(lèi)型: 有Undefined, Null, Boolean, Number和String。注意,描述中的英文單詞在這里僅指數(shù)據(jù)類(lèi)型的名稱(chēng),并不特指JS的全局對(duì)象N an, Boolean, Number, String等,它們?cè)诟拍钌系膮^(qū)別是比較大的。
    2010-10-10
  • JS實(shí)現(xiàn)移動(dòng)端整屏滑動(dòng)的實(shí)例代碼

    JS實(shí)現(xiàn)移動(dòng)端整屏滑動(dòng)的實(shí)例代碼

    本文通過(guò)實(shí)例代碼給大家分享了基于js 實(shí)現(xiàn)移動(dòng)端整屏滑動(dòng)效果,基本思路是檢測(cè)手指滑動(dòng)方向,獲取手指抬起時(shí)的位置,減去手指按下時(shí)的位置,得正即為向下滑動(dòng)了,具體實(shí)現(xiàn)代碼大家參考下本文
    2017-11-11
  • JS右下角廣告窗口代碼(可收縮、展開(kāi)及關(guān)閉)

    JS右下角廣告窗口代碼(可收縮、展開(kāi)及關(guān)閉)

    這篇文章主要介紹了JS右下角廣告窗口代碼,具有浮動(dòng)顯示、可收縮、展開(kāi)及關(guān)閉等功能,涉及javascript針對(duì)頁(yè)面元素屬性操作的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-09-09

最新評(píng)論

清镇市| 饶平县| 循化| 乾安县| 额济纳旗| 大丰市| 蒙山县| 墨脱县| 黎城县| 行唐县| 乳源| 南岸区| 晋江市| 甘南县| 临潭县| 宜宾市| 宁津县| 门头沟区| 安阳市| 南皮县| 桃江县| 潮州市| 深泽县| 兴国县| 阿拉善盟| 漳平市| 宣城市| 双峰县| 射阳县| 武隆县| 丹凤县| 定安县| 吉木萨尔县| 积石山| 普兰县| 宜宾市| 安义县| 嘉禾县| 淄博市| 怀柔区| 板桥市|