I want to check if the given string to my function is plain text or base64 format. I am able to encode a plain text to base64 format and reverse it. But I could not figure out any way to validate if the string is already base64 format. Can anyone please suggest correct way of doing this in node js? Is there any API for doing this already available in node js.
This works in Python: import base64 def IsBase64(str): try: base64. b64decode(str) return True except Exception as e: return False if IsBase64("ABC"): print("ABC is Base64-encoded and its result after decoding is: " + str(base64.
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}=))?
You are considering fooooooo and 12345678 plain text and not base64 string, while actually base64 encoded string itself is a plain text/string. Which means, fooooooo and 12345678 themselves are also base64 representation of some other strings.
Valid base64 strings are a subset of all plain-text strings. Assuming we have a character string, the question is whether it belongs to that subset. One way is what Basit Anwer suggests. Those libraries require installing libicu
though. A more portable way is to use the built-in Buffer
:
Buffer.from(str, 'base64')
Unfortunately, this decoding function will not complain about non-Base64 characters. It will just ignore non-base64 characters. So, it alone will not help. But you can try encoding it back to base64 and compare the result with the original string:
Buffer.from(str, 'base64').toString('base64') === str
This check will tell whether str
is pure base64 or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With