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}=))?$/;
console.log(base64regex.test("abc"));
console.log(base64regex.test("U29tZVN0cmluZ09idmlvdXNseU5vdEJhc2U2NEVuY29kZWQ="));
We define the base64regex
that matches any string that has 4 letters and numbers in the first group.
Then we check of groups of 2 letters and number or groups of 3 letters and numbers with equal signs after them for padding.
Therefore, the first console log will log false
.
And the 2nd one will log true
.