Skip to content

Commit

Permalink
fix(withoutTrailingSlash): consider qurry param (#219)
Browse files Browse the repository at this point in the history
* fix: consider scenario where / is part of query string in withoutTrailingSlash()

* revert change in `hasTrailingSlash`

---------

Co-authored-by: Pooya Parsa <[email protected]>
  • Loading branch information
thijsw and pi0 committed Mar 15, 2024
1 parent 69e26f8 commit 6cd1fcd
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 4 deletions.
7 changes: 3 additions & 4 deletions src/utils.ts
Expand Up @@ -93,7 +93,7 @@ export function hasTrailingSlash(
/**
* Removes trailing slash from the URL or pathname.
*
* If second argument is is true, it will only remove the trailing slash if it's not part of the query or fragment with cost of more expensive operations.
* If second argument is true, it will only remove the trailing slash if it's not part of the query or fragment with cost of more expensive operations.
*
* @example
*
Expand Down Expand Up @@ -123,10 +123,9 @@ export function withoutTrailingSlash(
fragment = input.slice(fragmentIndex);
}
const [s0, ...s] = path.split("?");
const cleanPath = s0.endsWith("/") ? s0.slice(0, -1) : s0;
return (
(s0.slice(0, -1) || "/") +
(s.length > 0 ? `?${s.join("?")}` : "") +
fragment
(cleanPath || "/") + (s.length > 0 ? `?${s.join("?")}` : "") + fragment
);
}

Expand Down
6 changes: 6 additions & 0 deletions test/trailing-slash.test.ts
Expand Up @@ -57,6 +57,8 @@ describe("withoutTrailingSlash, queryParams: false", () => {
"foo?123": "foo?123",
"foo/?123": "foo/?123",
"foo/?123#abc": "foo/?123#abc",
"foo/?k=v": "foo/?k=v",
"foo/?k=/": "foo/?k=",
};

for (const input in tests) {
Expand All @@ -81,6 +83,10 @@ describe("withoutTrailingSlash, queryParams: true", () => {
"foo?123": "foo?123",
"foo/?123": "foo?123",
"foo/?123#abc": "foo?123#abc",
"foo/?k=123": "foo?k=123",
"foo?k=/": "foo?k=/",
"foo/?k=/": "foo?k=/",
"foo/?k=/&x=y#abc": "foo?k=/&x=y#abc",
"/a/#abc": "/a#abc",
"/#abc": "/#abc",
};
Expand Down

0 comments on commit 6cd1fcd

Please sign in to comment.