export function isValidUrl(url: string): boolean {
try {
new URL(url);
return true;
} catch {
return false;
}
}
export function normalizeUrl(url: string): string {
const parsed = new URL(url);
parsed.hash = '';
if (parsed.pathname.endsWith('/') && parsed.pathname !== '/') {
parsed.pathname = parsed.pathname.slice(0, -1);
}
return parsed.toString();
}
export function getBaseDomain(url: string): string {
return new URL(url).origin;
}
export function isSameDomain(url1: string, url2: string): boolean {
return getBaseDomain(url1) === getBaseDomain(url2);
}
export function matchesPattern(url: string, patterns: string[]): boolean {
if (patterns.length === 0) return false;
return patterns.some(pattern => {
const regex = new RegExp(
pattern
.replace(/\*/g, '.*')
.replace(/\./g, '\\.')
.replace(/\?/g, '\\?')
);
return regex.test(url);
});
}
export function resolveUrl(base: string, relative: string): string {
try {
return new URL(relative, base).toString();
} catch {
return relative;
}
}