Skip to content Skip to sidebar Skip to footer

Determine If String Is In Base64 Using Javascript

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 valid base64? I would lik

Solution 1:

If you want to check whether it can be decoded or not, you can simply try decoding it and see whether it failed:

try {
    window.atob(str);
} catch(e) {
    // something failed// if you want to be specific and only catch the error which means// the base 64 was invalid, then check for 'e.code === 5'.// (because 'DOMException.INVALID_CHARACTER_ERR === 5')
}

Solution 2:

This should do the trick.

function isBase64(str) {
    if (str ==='' || str.trim() ===''){ returnfalse; }
    try {
        return btoa(atob(str)) == str;
    } catch (err) {
        returnfalse;
    }
}

Solution 3:

Building on @anders-marzi-tornblad'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

Update 2021

  • Following the comments below it transpires this regex-based solution provides a more accurate check than simply try`ing atob because the latter doesn't check for =-padding. According to RFC4648=-padding may only be ignored for base16-encoding or if the data length is known implicitely.
  • Regex-based solution also seems to be the fastest as hinted by kai. As jsperf seems flaky atm i made a new test on jsbench which confirms this.

Solution 4:

If "valid" means "only has base64 chars in it" then check against /[A-Za-z0-9+/=]/.

If "valid" means a "legal" base64-encoded string then you should check for the = at the end.

If "valid" means it's something reasonable after decoding then it requires domain knowledge.

Solution 5:

I would use a regular expression for that. Try this one:

/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/

Explanation:

^                          # Start of input
([0-9a-zA-Z+/]{4})*        # Groups of 4 valid characters decode# to 24 bits of data for each group
(                          # Either ending with:
    ([0-9a-zA-Z+/]{2}==)   # two valid characters followed by ==
    |                      # , or
    ([0-9a-zA-Z+/]{3}=)    # three valid characters followed by =
)?                         # , or nothing
$                          # End of input

Post a Comment for "Determine If String Is In Base64 Using Javascript"