Skip to content

Instantly share code, notes, and snippets.

@aloisdg
Last active November 14, 2022 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aloisdg/33043b0334e3991ab9d171d6716a0872 to your computer and use it in GitHub Desktop.
Save aloisdg/33043b0334e3991ab9d171d6716a0872 to your computer and use it in GitHub Desktop.
Add path to url
// https://stackoverflow.com/questions/27846195/how-can-i-add-the-current-pathname-to-a-href-with-a-different-url/74437330#74437330
// https://jsfiddle.net/t41z39fv/
const cases = [
["http://a.b", "a", "http://a.b/a"],
["http://a.b", "/a", "http://a.b/a"],
["http://a.b/", "a", "http://a.b/a"],
["http://a.b/a", "a", "http://a.b/a/a"],
["http://a.b/a/", "a", "http://a.b/a/a"],
["http://a.b", "a/a", "http://a.b/a/a"],
["http://a.b/", "a/a", "http://a.b/a/a"],
["http://a.b/a", "a/a", "http://a.b/a/a/a"],
["http://a.b/a/", "a/a", "http://a.b/a/a/a"],
["http://a.b/a/a", "a/a", "http://a.b/a/a/a/a"],
["http://a.b/a/a/", "a/a", "http://a.b/a/a/a/a"],
["http://a.b?", "/a", "http://a.b/a?"],
["http://a.b/?", "a", "http://a.b/a?"],
["http://a.b?a=b", "/a", "http://a.b/a?a=b"],
["http://a.b/?a=b", "a", "http://a.b/a?a=b"],
["http://a.b", "a b", "http://a.b/a%20b"],
["http://a.b", "/a b", "http://a.b/a%20b"],
]
const appendPath = (href, path) => {
if (!path) return href;
const url = new URL(href);
url.pathname += `${url.pathname.endsWith('/') ? "" : "/"}${path.startsWith('/') ? path.slice(1) : path}`
return url.href;
}
const fail = cases.find(([url, path, expected]) => {
const actual = appendPath(url, path);
if (actual !== expected) console.log(actual);
return actual !== expected;
})
console.log(fail ?? "success");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment