Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 like to be notified if the string is not base64 so I can perform a different action.

like image 947
Jonatan Avatar asked Oct 22 '11 14:10

Jonatan


People also ask

How do you check whether a string is Base64 encoded or not in JavaScript?

To determine if a string is a base64 string using JavaScript, we can check if a base64 string against a regex. For instance, we can write: const base64regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?

How do I check if a string is in Base64?

In base64 encoding, the character set is [A-Z, a-z, 0-9, and + /] . If the rest length is less than 4, the string is padded with '=' characters. ^([A-Za-z0-9+/]{4})* means the string starts with 0 or more base64 groups.

What is == in Base64?

The equals sign "=" represents a padding, usually seen at the end of a Base64 encoded sequence. The size in bytes is divisible by three (bits divisible by 24): All bits are encoded normally.


1 Answers

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') } 
like image 130
pimvdb Avatar answered Sep 29 '22 20:09

pimvdb