path-utils.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. /**
  2. * @private
  3. *
  4. *
  5. * @param {string} path
  6. * @returns {RegExpMatchArray}
  7. * @memberof pathUtils
  8. */
  9. function matchSlashes(path) {
  10. // https://regex101.com/r/Z21fEd/5
  11. return path.match(/^((\/+)?(.+?))(\/+)?$/);
  12. }
  13. /**
  14. *
  15. * @param {string} path
  16. * @returns {boolean}
  17. * @memberof pathUtils
  18. */
  19. export function hasHeadingSlash(path) {
  20. if (path === '') {
  21. return false;
  22. }
  23. const match = matchSlashes(path);
  24. return (match[2] != null);
  25. }
  26. /**
  27. *
  28. * @param {string} path
  29. * @returns {boolean}
  30. * @memberof pathUtils
  31. */
  32. export function hasTrailingSlash(path) {
  33. if (path === '') {
  34. return false;
  35. }
  36. const match = matchSlashes(path);
  37. return (match[4] != null);
  38. }
  39. /**
  40. *
  41. * @param {string} path
  42. * @returns {string}
  43. * @memberof pathUtils
  44. */
  45. export function addHeadingSlash(path) {
  46. if (path === '/') {
  47. return path;
  48. }
  49. if (!hasHeadingSlash(path)) {
  50. return `/${path}`;
  51. }
  52. return path;
  53. }
  54. /**
  55. *
  56. * @param {string} path
  57. * @returns {string}
  58. * @memberof pathUtils
  59. */
  60. export function addTrailingSlash(path) {
  61. if (path === '/') {
  62. return path;
  63. }
  64. if (!hasTrailingSlash(path)) {
  65. return `${path}/`;
  66. }
  67. return path;
  68. }
  69. /**
  70. *
  71. * @param {string} path
  72. * @returns {string}
  73. * @memberof pathUtils
  74. */
  75. export function removeTrailingSlash(path) {
  76. if (path === '/') {
  77. return path;
  78. }
  79. const match = matchSlashes(path);
  80. return match[1];
  81. }
  82. /**
  83. * A short-hand method to add heading slash and remove trailing slash.
  84. *
  85. * @param {string} path
  86. * @returns {string}
  87. * @memberof pathUtils
  88. */
  89. export function normalizePath(path) {
  90. if (path === '' || path === '/') {
  91. return '/';
  92. }
  93. const match = matchSlashes(path);
  94. if (match == null) {
  95. return '/';
  96. }
  97. return `/${match[3]}`;
  98. }
  99. /**
  100. *
  101. * @param {string} path
  102. * @returns {string}
  103. * @memberof pathUtils
  104. */
  105. export function attachTitleHeader(path) {
  106. return `# ${path}`;
  107. }