You can write something like my function below.
function getHostnameFromURI(url) {
// Check slashes in URL
if (url.indexOf('?') == -1 && !url.endsWith('/') || url.indexOf('#') == -1 && !url.endsWith('/')) {
url += '/';
}
let start = url.indexOf('://')+3;
let end = url.indexOf('/', start);
let domain = url.slice(start, end);
// Remove port specification from the URL
if (domain.indexOf(':') != -1) {
domain = domain.slice(0, domain.indexOf(':'));
}
return domain;
}
It correctly works with localhost, .co.uk, etc. domains.
https://stackoverflow.com/opensearch.xml --> stackoverflow.com
https://github.com/arichr --> github.com
Information: Please, check that your URLs are not wrong e.g. https://example.com?a=a
will return example.com?a=a