Skip to content

Instantly share code, notes, and snippets.

@duzun
Last active February 7, 2020 11:22
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 duzun/673906ee0dccc4f2fbef to your computer and use it in GitHub Desktop.
Save duzun/673906ee0dccc4f2fbef to your computer and use it in GitHub Desktop.
In Browser URL parser
/**
* Parse URLs in a Browser environment.
*
* Ussage:
* 1) var hostname = $url('https://duzun.me/playground', 'hostname');
*
* 2) var a = $url('https://duzun.me/playground?some=param');
* a.protocol = 'http:';
* var hrefSecured = a.href;
*/
function $url(href, part, doc) {
var a = url.a
, odoc = document
;
if (doc && doc !== odoc) {
a = doc.createElement('A');
}
else {
doc = odoc;
if(!a) url.a = a = doc.createElement('A');
}
if (href != null) {
if (href === '') href = doc.location.href; // IE interprets '' as base_url
a.href = href;
}
if (part === 'hash') {
if (part = a[part])
part = part.replace(/.*(?=#[^\s]*$)/, ''); // strip for ie7
return part;
}
return part ? a[part] : a;
} ;
@duzun
Copy link
Author

duzun commented Feb 7, 2020

Alternatively use new URL() in newer browsers or a lib like URL.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment