Last active
March 10, 2023 04:17
-
-
Save librz/8897da0d0d1f5e190d445a0e73390a13 to your computer and use it in GitHub Desktop.
Manipulate URL using JavaScript
This file contains hidden or 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
// this works but is quite messy and error prone | |
function getUrl(server: string, path: string, name: string, age: number): string { | |
const trimmedServer = server.endsWith("/") ? server.slice(0, -1) : server; // remove trialing slash if any | |
const origin = trimmedServer.startsWith("http") ? trimmedServer : `https://${trimmedServer}`; // add protocol if needed | |
const trimmedPath = path.endsWith("/") ? path.slice(0, -1) : path; // remove trialing slash if any | |
const realPath = trimmedPath.startsWith("/") ? trimmedPath : `/${trimmedPath}`; // add slash to begining if needed | |
const params = new URLSearchParams({ | |
name: name, | |
age: String(age) | |
}); | |
return `${origin}${realPath}?${params.toString()}` | |
} | |
// the pro way | |
function getUrl(server: string, path: string, name: string, age: number): string { | |
const base = server.startsWith("http") ? server : `https://${server}`; | |
const url = new URL(path, base); | |
url.searchParams.set("name", name); | |
url.searchParams.set("age", String(age)); | |
return url.toString(); // or url.href | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment