isBase64.js 650 B

1234567891011121314151617181920212223
  1. import assertString from './util/assertString';
  2. import merge from './util/merge';
  3. var notBase64 = /[^A-Z0-9+\/=]/i;
  4. var urlSafeBase64 = /^[A-Z0-9_\-]*$/i;
  5. var defaultBase64Options = {
  6. urlSafe: false
  7. };
  8. export default function isBase64(str, options) {
  9. assertString(str);
  10. options = merge(options, defaultBase64Options);
  11. var len = str.length;
  12. if (options.urlSafe) {
  13. return urlSafeBase64.test(str);
  14. }
  15. if (len % 4 !== 0 || notBase64.test(str)) {
  16. return false;
  17. }
  18. var firstPaddingChar = str.indexOf('=');
  19. return firstPaddingChar === -1 || firstPaddingChar === len - 1 || firstPaddingChar === len - 2 && str[len - 1] === '=';
  20. }