Skip to content

Instantly share code, notes, and snippets.

@duzun

duzun/url.js

Last active Feb 7, 2020
Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

@duzun 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