Last active
February 7, 2020 11:22
-
-
Save duzun/673906ee0dccc4f2fbef to your computer and use it in GitHub Desktop.
In Browser URL parser
This file contains 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
/** | |
* 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; | |
} ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Alternatively use
new URL()
in newer browsers or a lib like URL.js