Skip to content

Commit bd38ab2

Browse files
authored
Omit paths and query params when formatting clean URLs for display (#728)
1 parent 8cf2945 commit bd38ab2

2 files changed

Lines changed: 11 additions & 10 deletions

File tree

web/src/lib/utils/__tests__/formatCleanUrl.test.ts

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,15 @@ describe("formatCleanUrl", () => {
1515
expect(formatCleanUrl("https://namesake.fyi/")).toBe("namesake.fyi");
1616
});
1717

18-
it("removes only a single trailing slash at the end", () => {
19-
expect(formatCleanUrl("https://example.com/path/")).toBe(
20-
"example.com/path",
21-
);
22-
});
23-
2418
it("leaves host-only strings unchanged", () => {
2519
expect(formatCleanUrl("example.com")).toBe("example.com");
2620
});
2721

28-
it("returns empty string for empty input", () => {
29-
expect(formatCleanUrl("")).toBe("");
22+
it("omits the path, query, and fragment", () => {
23+
expect(
24+
formatCleanUrl(
25+
"https://law.uic.edu/experiential-education/clinics/pro-bono/projects/?source=directory#services",
26+
),
27+
).toBe("law.uic.edu");
3028
});
3129
});
Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
11
/**
2-
* Given a URL, return the URL without protocol, "www", or trailing slash.
2+
* Given a URL or hostname, return its hostname without "www".
33
*
44
* @example
55
* formatCleanUrl("https://www.masstpc.org/")
66
* // "masstpc.org"
77
*/
88
export function formatCleanUrl(url: string): string {
9-
return url.replace(/^https?:\/\/(www\.)?/, "").replace(/\/$/, "");
9+
// Ensure handling of links that are already hostnames without typeerror
10+
const absoluteUrl = url.includes("://") ? url : `https://${url}`;
11+
12+
return new URL(absoluteUrl).hostname.replace(/^www\./, "");
1013
}

0 commit comments

Comments
 (0)