Detect base64 encoding

Does anyone know of a jQuery plugin that can check if base64 code is randomly encoded? I want to be able to decode base64 strings, but only if the string is encoded to begin with. I see several scripts that can encode and decode, but I can really check if the string is encoded.

Is there such a thing?

+5
source share
3 answers

Should it be a jQuery plugin? Just use simple JavaScript regular expression:

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 likely base64 encoded.
} else {
    // It definitely not base64 encoded.
}

A sample regex is taken from this question: RegEx to analyze or validate Base64 data .

+10
source

(= ==) . , .

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})?$");

+3

I know that it may be too late to answer, but this is what I came to. In this case, I use {match} in jQuery. This applies to images or texts. Hope this helps

var sSampleBase64Text = 'data:text/plain;base64,MSkgTG9naW4gRGV0YWlscwogPj4gdGNfYWRtaW5fYXllZQogPj4gdHdpbmtsZXMyMnRo';
var mCheckMatchResult = sSampleBase64Text.match(/^(?:[data]{4}:(text|image|application)\/[a-z]*)/);

var sAlertMessage = 'Valid base 64 encode string';
if (mCheckMatchResult === null || mCheckMatchResult.length <= 0) {
     sAlertMessage = 'Not a valid base 64 encode string';
} 

$('.result').append('<p>' + sAlertMessage + '</p>');

Try looking here: https://jsfiddle.net/lajatomary/a8tugwe3/4/

0
source

All Articles