Base64 Encoded String Regular Expression

A regular expression that matches a valid Base64 encoded string.

/^\s*data:(?:[a-z]+\/[a-z0-9-+.]+(?:;[a-z-]+=[a-z0-9-]+)?)?(?:;base64)?,([a-z0-9!$&',()*+;=\-._~:@/?%\s]*?)\s*$/i

What Is Base64:

Base64 is a group of binary-to-text encoding schemes that represent binary data (more specifically, a sequence of 8-bit bytes) in an ASCII string format by translating the data into a radix-64 representation.

The term Base64 originates from a specific MIME content transfer encoding.

Each non-final Base64 digit represents exactly 6 bits of data.

Three 8-bit bytes (i.e., a total of 24 bits) can therefore be represented by four 6-bit Base64 digits.

Base64 Data Example:

  • data:image/gif;base64,xxxx==