Hey is a decentralized and permissionless social media app built with Lens Protocol 🌿

Refactor truncateUrl helper for improved error handling and URL parsing logic

yoginth.com 04892ea4 8d5626af

verified
+17 -10
+17 -10
apps/web/src/helpers/truncateUrl.ts
··· 1 1 const truncateUrl = (url: string, maxLength: number): string => { 2 - const strippedUrl = url 3 - .replace(/^(http|https):\/\//, "") 4 - .replace(/^www\./, ""); 2 + try { 3 + const parsed = new URL(url); 4 + const stripped = 5 + `${parsed.host}${parsed.pathname}${parsed.search}${parsed.hash}`.replace( 6 + /^www\./, 7 + "" 8 + ); 5 9 6 - if (new URL(url).hostname.endsWith("hey.xyz")) { 7 - return strippedUrl; 8 - } 10 + if (parsed.hostname.endsWith("hey.xyz")) return stripped; 9 11 10 - if (strippedUrl.length > maxLength) { 11 - return `${strippedUrl.substring(0, maxLength - 1)}…`; 12 + return stripped.length > maxLength 13 + ? `${stripped.slice(0, maxLength - 1)}…` 14 + : stripped; 15 + } catch { 16 + // fallback: remove protocol/www, truncate if needed 17 + const stripped = `${url.replace(/^(https?:\/\/)?(www\.)?/, "")}`; 18 + return stripped.length > maxLength 19 + ? `${stripped.slice(0, maxLength - 1)}…` 20 + : stripped; 12 21 } 13 - 14 - return strippedUrl; 15 22 }; 16 23 17 24 export default truncateUrl;