normalize-url.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. "use strict";
  2. /**
  3. * @param {string[]} pathComponents path components
  4. * @returns {string} normalized url
  5. */
  6. function normalizeUrlInner(pathComponents) {
  7. return pathComponents.reduce(function (accumulator, item) {
  8. switch (item) {
  9. case "..":
  10. accumulator.pop();
  11. break;
  12. case ".":
  13. break;
  14. default:
  15. accumulator.push(item);
  16. }
  17. return accumulator;
  18. }, /** @type {string[]} */[]).join("/");
  19. }
  20. /**
  21. * @param {string} urlString url string
  22. * @returns {string} normalized url string
  23. */
  24. module.exports = function normalizeUrl(urlString) {
  25. urlString = urlString.trim();
  26. if (/^data:/i.test(urlString)) {
  27. return urlString;
  28. }
  29. var protocol =
  30. // eslint-disable-next-line unicorn/prefer-includes
  31. urlString.indexOf("//") !== -1 ? "".concat(urlString.split("//")[0], "//") : "";
  32. var components = urlString.replace(new RegExp(protocol, "i"), "").split("/");
  33. var host = components[0].toLowerCase().replace(/\.$/, "");
  34. components[0] = "";
  35. var path = normalizeUrlInner(components);
  36. return protocol + host + path;
  37. };