Last active
August 29, 2015 14:10
-
-
Save fraserharris/82e34f3fa4062bd7c9ac to your computer and use it in GitHub Desktop.
This file contains hidden or 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
// Safari reports "0" when no port is in the href | |
// IE reports "80" when no port is in the href | |
function getPortUsingSingleTernaryOp (url) { | |
var port, a = document.createElement('a'); | |
a.href = url; | |
return (url.indexOf(":" + a.port) > -1) ? a.port : ""; | |
} | |
function getPortUsingTernaryOp (url) { | |
var port, a = document.createElement('a'); | |
a.href = url; | |
return ( | |
a.port == "" || a.port == "0"? "" : | |
a.port == "80" && url.indexOf(":" + a.port) >= 0? "" : | |
a.port ); | |
} | |
function getPortUsingSwitch (url) { | |
// Safari reports "0" when no port is in the href | |
// IE reports "80" when no port is in the href | |
var port, a = document.createElement('a'); | |
a.href = url; | |
// using switch | |
switch (a.port) { | |
case "0": port = (url.indexOf(":0") > -1) ? "0" : ""; break; | |
case "80": port = (url.indexOf(":80") > -1) ? "80" : ""; break; | |
default: port = a.port; | |
} | |
return port; | |
} | |
function getPortUsingObjectLiteral (url) { | |
// Safari reports "0" when no port is in the href | |
// IE reports "80" when no port is in the href | |
var port, a = document.createElement('a'); | |
a.href = url; | |
// using object literal | |
var portDefaults = { | |
'0': function () { return (url.indexOf(":0") > -1) ? "0" : ""; }, | |
'80': function () { return (url.indexOf(":80") > -1) ? "80" : ""; } | |
}; | |
if (typeof portDefaults[a.port] !== 'function') { | |
port = a.port; | |
} else { | |
port = portDefaults[a.port](); | |
} | |
return port; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment