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 -->
Post a Comment for "Getting Port From Url String Using Javascript"