Skip to content Skip to sidebar Skip to footer

Getting Port From Url String Using Javascript

I would like a function in javascript that will get as a parameter an url and will return the port of that URL as it follows: If there's a http or https (port 80 / 443) it won't b

Solution 1:

Here is a regex based solution (the regex is not bullet proof):

var urls = [
  "http://localhost/path/",
  "https://localhost/",
  "http://localhost:8080",
  "https://localhost:8443/path",
  "ftp://localhost/"
];
var i;
for (i = 0; i < urls.length; i++) {
  console.log(urls[i], getPortFromURL(urls[i]));
}

functiongetPortFromURL(url) {
  var regex = /^(http|https):\/\/[^:\/]+(?::(\d+))?/;
  var match = url.match(regex);
  if (match === null) {
    returnnull;
  } else {
    return match[2] ? match[2] : {http: "80", https: "443"}[match[1]];
  }
}
<!-- nothing here, see console -->

Solution 2:

hope the following code will help

function getPort(){
var port==location.port;
if(port=="")
{
if(location.protocol=="http:")
  return"80";
elsereturn"443";
return port;
}

Post a Comment for "Getting Port From Url String Using Javascript"