Skip to content

Instantly share code, notes, and snippets.

@jkarttunen
Created April 12, 2020 07:19
Show Gist options
  • Save jkarttunen/bcb16528075295721446d57ff8cbc400 to your computer and use it in GitHub Desktop.
Save jkarttunen/bcb16528075295721446d57ff8cbc400 to your computer and use it in GitHub Desktop.
Get subdomain from hostname
/**
* Extracts subdomain from hostname. Works with localhost, but not with full url with ports.
* @example
* getSubdomain(location.hostname); //www.google.com
* // returns 'www'
* @example
* getSubdomain(location.hostname); //localhost
* // returns 'localhost'
**/
function getSubdomain(hostname) {
const regexParse = new RegExp('[a-z-0-9]{2,63}.[a-z.]{2,5}$');
const urlParts = regexParse.exec(hostname);
return subdomain hostname.replace(urlParts[0],'').slice(0, -1) || hostname;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment