Determine if string is in base64 using JavaScript

前端 未结 10 1416
悲哀的现实
悲哀的现实 2020-12-28 14:38

I\'m using the window.atob(\'string\') function to decode a string from base64 to a string. Now I wonder, is there any way to check that \'string\' is actually

相关标签:
10条回答
  • 2020-12-28 14:59

    This should do the trick.

    function isBase64(str) {
        if (str ==='' || str.trim() ===''){ return false; }
        try {
            return btoa(atob(str)) == str;
        } catch (err) {
            return false;
        }
    }
    
    0 讨论(0)
  • 2020-12-28 15:05

    As there are mostly two possibilities posted here (regex vs try catch) I did compare the performance of both: https://jsperf.com/base64-check/

    Regex solution seems to be much faster and clear winner. Not sure if the regex catches all cases but for my tests it worked perfectly.

    Thanks to @Philzen for the regex!

    p.s.

    In case someone is interested in finding the fastest way to safely decode a base64 string (that's how I came here): https://jsperf.com/base64-decoding-check

    0 讨论(0)
  • 2020-12-28 15:05

    For me a string is likely an encoded base64 if:

    1. it's length is divisible by 4
    2. uses A-Z a-z 0-9 +/=
    3. only uses = in the end (0-3 chars)

    so the code would be

    function isBase64(str)
    {
        return str.length % 4 == 0 && /^[A-Za-z0-9+/]+[=]{0,3}$/.test(str);
    }
    
    0 讨论(0)
  • 2020-12-28 15:07

    I know its late, but I tried to make it simple here;

    function isBase64(encodedString) {
        var regexBase64 = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
        return regexBase64.test(encodedString);   // return TRUE if its base64 string.
    }
    
    0 讨论(0)
  • 2020-12-28 15:08

    Building on @atornblad's answer, using the regex to make a simple true/false test for base64 validity is as easy as follows:

    var base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
    
    base64regex.test("SomeStringObviouslyNotBase64Encoded...");             // FALSE
    base64regex.test("U29tZVN0cmluZ09idmlvdXNseU5vdEJhc2U2NEVuY29kZWQ=");   // TRUE
    
    0 讨论(0)
  • 2020-12-28 15:12

    This is how it's done in one of my favorite validation libs:

    const notBase64 = /[^A-Z0-9+\/=]/i;
    
    export default function isBase64(str) {
      assertString(str); // remove this line and make sure you pass in a string
      const len = str.length;
      if (!len || len % 4 !== 0 || notBase64.test(str)) {
        return false;
      }
      const firstPaddingChar = str.indexOf('=');
      return firstPaddingChar === -1 ||
        firstPaddingChar === len - 1 ||
        (firstPaddingChar === len - 2 && str[len - 1] === '=');
    }
    

    https://github.com/chriso/validator.js/blob/master/src/lib/isBase64.js

    0 讨论(0)
提交回复
热议问题