Handle malformed article URLs

This commit is contained in:
Anthony
2025-11-27 21:18:43 +08:00
parent 7f75b44af1
commit 061474c574
6 changed files with 3030 additions and 19 deletions

23
utils/url.ts Normal file
View File

@@ -0,0 +1,23 @@
export const normalizeUrl = (url: string) => {
let cleanUrl = url.trim();
if (!cleanUrl.startsWith('http://') && !cleanUrl.startsWith('https://')) {
return `https://${cleanUrl}`;
}
return cleanUrl;
};
export const getDisplayUrl = (url: string): { href: string; hostname: string } => {
const normalized = normalizeUrl(url);
try {
const parsed = new URL(normalized);
return { href: normalized, hostname: parsed.hostname };
} catch {
try {
const fallback = new URL(url);
return { href: url, hostname: fallback.hostname };
} catch {
return { href: url, hostname: url };
}
}
};