index.js 901 B

1234567891011121314151617181920212223242526272829303132333435
  1. "use strict";
  2. /**
  3. * protocols
  4. * Returns the protocols of an input url.
  5. *
  6. * @name protocols
  7. * @function
  8. * @param {String|URL} input The input url (string or `URL` instance)
  9. * @param {Boolean|Number} first If `true`, the first protocol will be returned. If number, it will represent the zero-based index of the protocols array.
  10. * @return {Array|String} The array of protocols or the specified protocol.
  11. */
  12. module.exports = function protocols(input, first) {
  13. if (first === true) {
  14. first = 0;
  15. }
  16. var prots = "";
  17. if (typeof input === "string") {
  18. try {
  19. prots = new URL(input).protocol;
  20. } catch (e) {}
  21. } else if (input && input.constructor === URL) {
  22. prots = input.protocol;
  23. }
  24. var splits = prots.split(/\:|\+/).filter(Boolean);
  25. if (typeof first === "number") {
  26. return splits[first];
  27. }
  28. return splits;
  29. };