url.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. export const cleanPath = (text) => {
  2. return text.replace(/([^:])(\/\/+)/g, '$1/');
  3. };
  4. export const isURL = (text) => {
  5. // old: /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/
  6. return /^https?:\/\//i.test(text);
  7. };
  8. export const generateUrl = (baseUrl, slug) => {
  9. return isURL(slug) ? cleanPath(slug) : cleanPath(`${baseUrl}/${slug}`);
  10. };
  11. /**
  12. * Checks whether a url is next.js specific or not
  13. * @param path path check
  14. */
  15. export const isNextInternalUrl = (path) => {
  16. return new RegExp(/[^/]*^.[_]|^\/(404|500)$|\/_middleware$|(?:\[)/g).test(path);
  17. };
  18. /**
  19. * Creates a replace function to replace the default locale
  20. * Avoids creating the same RegExp within each replace
  21. *
  22. * Replaces only if the path does not contain the locale as an actual valid path
  23. *
  24. * Given a default locale of en-US it replaces:
  25. * /en-US -> /
  26. * /en-US/home -> /home
  27. * /en-US/home/ -> /home/
  28. *
  29. * Does not replace if its actual page
  30. * /en-USA -> /en-USA
  31. * /en-USA/home -> /en-USA/home
  32. * /en-US-home -> /en-US-home
  33. *
  34. * @param defaultLocale defaultLocale as provided by i18n within next config
  35. */
  36. export const createDefaultLocaleReplace = (defaultLocale) => {
  37. const defaultLocaleRegExp = new RegExp(`^/${defaultLocale}($|/)`);
  38. return (path) => path.replace(defaultLocaleRegExp, '/');
  39. };
  40. /**
  41. * Return UTF-8 encoded urls
  42. * @param path
  43. * @returns
  44. * @link https://developers.google.com/search/docs/advanced/sitemaps/build-sitemap#general-guidelines
  45. */
  46. export const entityEscapedUrl = (path) => {
  47. return path
  48. .replace(/&/g, '&')
  49. .replace(/'/g, ''')
  50. .replace(/"/g, '"')
  51. .replace(/>/g, '>')
  52. .replace(/</g, '&lt;');
  53. };