You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.ts 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. /**
  2. * Gets a {@link URL} without hash and query/search params from a specific
  3. * {@code URL}.
  4. *
  5. * @param {URL} url - The {@code URL} which may have hash and query/search
  6. * params.
  7. * @returns {URL}
  8. */
  9. export function getURLWithoutParams(url: URL): URL {
  10. const { hash, search } = url;
  11. if ((hash && hash.length > 1) || (search && search.length > 1)) {
  12. url = new URL(url.href); // eslint-disable-line no-param-reassign
  13. url.hash = '';
  14. url.search = '';
  15. // XXX The implementation of URL at least on React Native appends ? and
  16. // # at the end of the href which is not desired.
  17. let { href } = url;
  18. if (href) {
  19. href.endsWith('#') && (href = href.substring(0, href.length - 1));
  20. href.endsWith('?') && (href = href.substring(0, href.length - 1));
  21. // eslint-disable-next-line no-param-reassign
  22. url.href === href || (url = new URL(href));
  23. }
  24. }
  25. return url;
  26. }
  27. /**
  28. * Gets a URL string without hash and query/search params from a specific
  29. * {@code URL}.
  30. *
  31. * @param {URL} url - The {@code URL} which may have hash and query/search
  32. * params.
  33. * @returns {string}
  34. */
  35. export function getURLWithoutParamsNormalized(url: URL): string {
  36. const urlWithoutParams = getURLWithoutParams(url).href;
  37. if (urlWithoutParams) {
  38. return urlWithoutParams.toLowerCase();
  39. }
  40. return '';
  41. }