Skip to content

Instantly share code, notes, and snippets.

@pinkhominid
Last active March 18, 2019 22:10
Show Gist options
  • Save pinkhominid/52275679d68de878e560386270ac8be4 to your computer and use it in GitHub Desktop.
Save pinkhominid/52275679d68de878e560386270ac8be4 to your computer and use it in GitHub Desktop.
Parsing a URL (2019-edition)
const encodedDestHref = encodeURIComponent('https://example.com/#/hash/path?hparam1=a&hparam2=b');
location.href = `https://example.com/path?dest=${encodedDestHref}`;
const searchParams = new URLSearchParams(location.search);
const destHref = searchParams.get('dest');
const destUrl = new URL(destHref);
const hashRelativeUrl = new URL(destUrl.hash.substr(1), destUrl.origin); //hack
console.log(hashRelativeUrl.pathname); // '/hash/path'
console.log(hashRelativeUrl.search); // '?hparam1=a&hparam2=b'
console.log(hashRelativeUrl.searchParams.get('hparam2')); // 'b'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment