Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect base64 encoding

Does anyone know of a jQuery plugin that can check if text is base64 encoded by chance? I want to be able to decode base64 strings but only if the string is encoded to begin with. I see several scripts out there that can encode and decode but I really one that can check if the string is encoded.

Does such a thing exist?

like image 924
Nick Avatar asked Dec 03 '22 07:12

Nick


2 Answers

Must it really be a jQuery plugin? Just use a simple JavaScript regex match:

var base64Matcher = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})$");

// ...

if (base64Matcher.test(someString)) {
    // It's likely base64 encoded.
} else {
    // It's definitely not base64 encoded.
}

The regex pattern is taken from this question: RegEx to parse or validate Base64 data.

like image 72
BalusC Avatar answered Dec 18 '22 05:12

BalusC


The above answer didn't count for the padding with equals signs (= or ==) at the end of the string for me. I've updated the query and the following works for me.

var base64Matcher = new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{4})([=]{1,2})?$");

like image 22
Branndon Avatar answered Dec 18 '22 06:12

Branndon