sparkast/lib/normalizeURL.ts
2024-03-31 14:02:42 +08:00

20 lines
621 B
TypeScript

export function normalizeURL(input: string): string {
try {
// try to create a URL object
const url = new URL(input);
// if the URL is valid, return it
return url.href;
} catch (error) {
// if the URL is invalid, try to add the protocol
const withHTTP = "http://" + input;
try {
const urlWithHTTP = new URL(withHTTP);
return urlWithHTTP.href;
} catch (error) {
// if the URL is still invalid, return the original input
console.error("Invalid URL:", input);
return input;
}
}
}