Skip to content

Instantly share code, notes, and snippets.

@fraserharris
Last active August 29, 2015 14:10
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 fraserharris/82e34f3fa4062bd7c9ac to your computer and use it in GitHub Desktop.
Save fraserharris/82e34f3fa4062bd7c9ac to your computer and use it in GitHub Desktop.
// 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