Last active
November 14, 2022 20:51
-
-
Save aloisdg/33043b0334e3991ab9d171d6716a0872 to your computer and use it in GitHub Desktop.
Add path to url
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
// 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