Last active
October 6, 2016 16:32
-
-
Save englishextra/4e9a0498772f05fa5d45cfcc0d8be5dd to your computer and use it in GitHub Desktop.
Unified URL parsing API in the browser and node
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
/*! | |
* modified for babel Unified URL parsing API in the browser and node | |
* github.com/wooorm/parse-link | |
* removed AMD, CommonJS support | |
* gist.github.com/englishextra/4e9a0498772f05fa5d45cfcc0d8be5dd | |
* gist.github.com/englishextra/2a7fdabd0b23a8433d5fc148fb788455 | |
* jsfiddle.net/englishextra/fcdds4v6/ | |
* @param {String} url URL string | |
* @param {Boolean} [true|false] if true, returns protocol:, :port, /pathname, ?search, ?query, #hash | |
* if set to false, returns protocol, port, pathname, search, query, hash | |
* alert(parseLink("http://localhost/search?s=t&v=z#dev").href| | |
* origin|host|port|hash|hostname|pathname|protocol|search|query|isAbsolute|isRelative|isCrossDomain); | |
*/ | |
var parseLink = function (url,full) { | |
full = full || !1; | |
var g = function () { | |
var _r = function (s) { | |
return s.replace(/^(#|\?)/, "").replace(/\:$/, ""); | |
}, | |
l = location || "", | |
_p = function (protocol) { | |
switch (protocol) { | |
case "http:": | |
return full ? ":" + 80 : 80; | |
case "https:": | |
return full ? ":" + 443 : 443; | |
default: | |
return full ? ":" + l.port : l.port; | |
} | |
}, | |
_s = (0 == url.indexOf("//") || !!~url.indexOf("://")), | |
w = window.location || "", | |
_o = function () { | |
var o = w.protocol + "//" + w.hostname + (w.port ? ":" + w.port : ""); | |
return o || ""; | |
}, | |
_c = function () { | |
var c = document.createElement("a"); | |
c.href = url; | |
var v = c.protocol + "//" + c.hostname + (c.port ? ":" + c.port : ""); | |
return v !== _o(); | |
}, | |
a = document.createElement("a"); | |
a.href = url; | |
return { | |
href : a.href, | |
origin : _o(), | |
host : a.host || l.host, | |
port : ("0" === a.port || "" === a.port) ? _p(a.protocol) : (full ? a.port : _r(a.port)), | |
hash : full ? a.hash : _r(a.hash), | |
hostname : a.hostname || l.hostname, | |
pathname : a.pathname.charAt(0) != "/" ? (full ? "/" + a.pathname : a.pathname) : (full ? a.pathname : a.pathname.slice(1)), | |
protocol : !a.protocol || ":" == a.protocol ? (full ? l.protocol : _r(l.protocol)) : (full ? a.protocol : _r(a.protocol)), | |
search : full ? a.search : _r(a.search), | |
query : full ? a.search : _r(a.search), | |
isAbsolute : _s, | |
isRelative : !_s, | |
isCrossDomain : _c(), | |
hasHTTP : /^(http|https):\/\//i.test(url) ? !0 : !1 | |
}; | |
}; | |
return g(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment