parse-content-type.js 834 B

123456789101112131415161718192021222324252627282930
  1. import {Errorf} from '@e22m4u/js-format';
  2. /**
  3. * Parse content type.
  4. *
  5. * @param {string} input
  6. * @returns {{
  7. * boundary: string|undefined,
  8. * charset: string|undefined,
  9. * mediaType: string|undefined,
  10. * }}
  11. */
  12. export function parseContentType(input) {
  13. if (typeof input !== 'string')
  14. throw new Errorf(
  15. 'The parameter "input" of "parseContentType" ' +
  16. 'should be a String, but %v was given.',
  17. input,
  18. );
  19. const res = {mediaType: undefined, charset: undefined, boundary: undefined};
  20. const re =
  21. /^\s*([^\s;/]+\/[^\s;/]+)(?:;\s*charset=([^\s;]+))?(?:;\s*boundary=([^\s;]+))?.*$/i;
  22. const matches = re.exec(input);
  23. if (matches && matches[1]) {
  24. res.mediaType = matches[1];
  25. if (matches[2]) res.charset = matches[2];
  26. if (matches[3]) res.boundary = matches[3];
  27. }
  28. return res;
  29. }