JSFiddle - React, Tailwind, and code Playground

by jfriend00

HTML

<div id="result"></div>

JavaScript

var urls = [
    "http://www.websitename.com",
    "https://www.websitename.com",
    "websitename.com",
    "http://www.websitename.com/filename",
    "subdomain.websitename.com",
    "http://www.websitename.com:80"
];

function log(x) {
    $("#result").append(x + "<br>");
}

function getDomain(url) {
    var prefix = /^https?:\/\//;
    var domain = /^[^\/:]+/;
    // remove any prefix
    url = url.replace(prefix, "");
    // assume any URL that starts with a / is on the current page's domain
    if (url.charAt(0) === "/") {
        url = window.location.hostname + url;
    }
    // now extract just the domain
    var match = url.match(domain);
    if (match) {
        return(match[0]);
    }
    return(null);
}


for (var i = 0; i < urls.length; i++) {
    log(getDomain(urls[i]));
}