Avatar of MJ
MJ
Flag for United States of America asked on

Get subdomain with domain if it exists?

I want to capture the sub domain if it exists? I currently can get domain:

var currDD = document.domain;
currDD=currDD.split(".").slice(-2).join(".");

but not sure how to tell if sub domain exists and capture it conditionally?
JavaScript

Avatar of undefined
Last Comment
lightspeedvt

8/22/2022 - Mon
nap0leon

Crude example:
<script type="text/javascript">
var URL = window.location.href;
var domain = document.domain;
//var domain = "my.subdomain.mysite.com"
//var domain = "subdomain.mysite.com"
var arrDomain = domain.split('.')
var domainLength = arrDomain.length;

if (domainLength > 2) {
    for (i=0;i<domainLength-2;i++){
      document.write(arrDomain[i])
      if (i != domainLength-3) { document.write('.') }
    }
} else {
    document.write('no subdomain')
}
</script>

Open in new window

MJ

ASKER
I need to capture the sub domain if present. Examples:

"www.subdomain.mysite.com" -->   "subdomain.mysite.com"


"www..mysite.com" -->   "mysite.com"
lightspeedvt

This can be achieved via Regular Expressions:

var currDD = document.domain;
var patt = /(?:[w]{3}\.)?([^.]+)\..*\./gi
subdomain=patt.exec(currDD)[1];

Open in new window


Sure, a lot of people can make much better RegExp pattern.
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
MJ

ASKER
won't window.location.hostname work?
ASKER CERTIFIED SOLUTION
lightspeedvt

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.