Skip to content

Instantly share code, notes, and snippets.

@killedbymemory
Created July 1, 2019 08:10
Show Gist options
  • Save killedbymemory/7e934e01c8e3aaa8d23492fb964e8d73 to your computer and use it in GitHub Desktop.
Save killedbymemory/7e934e01c8e3aaa8d23492fb964e8d73 to your computer and use it in GitHub Desktop.
Subdomain extractor
function getRealmIdentifier(hostname, {defaultIdentifier = "gdis", baseDomain = "example.local"} = {}, debug = false) {
const _baseDomain = baseDomain.replace('.', '\\.');
const pattern = new RegExp(`^(?:www\\.)?([^:\\/?\\n\\.]+)\\.${baseDomain}$`, 'i');
const result = hostname.match(pattern);
debug && console.info(hostname, defaultIdentifier, baseDomain, pattern, result);
if (result === null) {
return defaultIdentifier;
}
const [_, subdomain] = result;
return subdomain;
};
console.info(getRealmIdentifier("www.gdis.example.local") === "gdis");
console.info(getRealmIdentifier("gdis.example.local") === "gdis");
console.info(getRealmIdentifier("dcwc.example.local") === "dcwc");
console.info(getRealmIdentifier("www.dcwc.example.local") === "dcwc");
console.info(getRealmIdentifier("www.dcwc.example.org", {baseDomain: "example.org"}) === "dcwc");
console.info(getRealmIdentifier("www.dcwc.staging.example.org", {baseDomain: "staging.example.org"}) === "dcwc");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment