Created
April 12, 2020 07:19
-
-
Save jkarttunen/bcb16528075295721446d57ff8cbc400 to your computer and use it in GitHub Desktop.
Get subdomain from hostname
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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