Last active
February 6, 2021 00:15
-
-
Save pinkhominid/742ff38688f7638d4eb795048b620e8e to your computer and use it in GitHub Desktop.
URL fun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"version": "0.3.0", | |
"name": "url-fun", | |
"description": "URL fun", | |
"main": "url-fun.js", | |
"author": "pinkhominid <pinkhominid@birdbomb.com>", | |
"license": "MIT", | |
"homepage": "https://gist.github.com/pinkhominid/742ff38688f7638d4eb795048b620e8e" | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function toAbsUrl(rel, base) { | |
return (new URL(rel, base)).toString() | |
} | |
export function toRelUrl(abs) { | |
const url = new URL(abs); | |
return url.toString().substring(url.origin.length); | |
}; | |
export function isLocalUrl(url) { | |
const { hostname } = new URL(url); | |
return /^(localhost|127\.0\.0\.1|0\.0\.0\.0)$/.test(hostname); | |
} | |
export function getSecondAndTopLevelDomain(url) { | |
const { hostname } = new URL(url); | |
// TODO: if (isIP(hostname)) return undefined; | |
return hostname.replace(/^.*(\b[^.]+\.[^.]+)$/, '$1'); | |
} | |
export function areUrlOriginsEqual(url1, url2) { | |
const u1 = new URL(url1); | |
const u2 = new URL(url2); | |
return u1.origin === u2.origin; | |
} | |
const trailingSlashesPathReplacePtn = /\/+$/; | |
// trailing slash path insensitive equality | |
export function areUrlsEqualish(url1, url2) { | |
const u1 = new URL(url1); | |
const u2 = new URL(url2); | |
u1.pathname = u1.pathname.replace(trailingSlashesPathReplacePtn, ''); | |
u2.pathname = u2.pathname.replace(trailingSlashesPathReplacePtn, ''); | |
return u1.toString() === u2.toString(); | |
} | |
export function mergeURLSearchParams(...paramCollections) { | |
let paramsObj; | |
for (const collection of paramCollections) { | |
paramsObj = { ...paramsObj, ...Object.fromEntries(new URLSearchParams(collection)) }; | |
} | |
return new URLSearchParams(paramsObj).toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
npm i gist:742ff38688f7638d4eb795048b620e8e