Skip to content

Instantly share code, notes, and snippets.

@kevsersrca
Created November 28, 2019 08:24
Show Gist options
  • Save kevsersrca/102047323cdb4befa66dbfcb031f2e61 to your computer and use it in GitHub Desktop.
Save kevsersrca/102047323cdb4befa66dbfcb031f2e61 to your computer and use it in GitHub Desktop.
extract hostname
function extractHostname(url) {
var hostname;
//find & remove protocol (http, ftp, etc.) and get hostname
if (url.indexOf("//") > -1) {
hostname = url.split('/')[2];
}
else {
hostname = url.split('/')[0];
}
//find & remove port number
hostname = hostname.split(':')[0];
//find & remove "?"
hostname = hostname.split('?')[0];
return hostname;
}
@kevsersrca
Copy link
Author

const getHostnameFromRegex = (url) => {
  // run against regex
  const matches = url.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
  // extract hostname (will be null if no match is found)
  return matches && matches[1];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment