DEV Community

loading...

Need help cleaning up this code, which modifies the subdomain.

DeChamp
Just a coder and a dad. I love my family and I love to code!!!! started coding at 11, so I have 25 years under my belt. Still love learning about it every day. Black lives matter!
・1 min read

Goal would be to get one subdomain and swap it out for another. I feel there has to be a cleaner way to do this. help me out!

var url = window.location;

// example doamin would have a subdomain so https://auth.domain.ext
var domain = url.host;
var domainParts = domain.split('.');
var mainDomainParts = domainParts.slice(domainParts.length - 2, domainParts.length);
mainDomainParts.unshift('admin');
var adminDomain = mainDomainParts.join('.');
var fullAdminDomain = url.protocol + '//' + adminDomain;
Enter fullscreen mode Exit fullscreen mode

Discussion (4)

Collapse
kspeakman profile image
Kasey Speakman • Edited
var subdomainMatch = /^[^.]+\./;
var admin = window.location.host.replace(subdomainMatch, "admin.");

This is using a regex, but at least it is a small one.

op meaning
^ line starts with
[^ any character except the following
. the character .
] end of character list
+ match one or more of the preceding (any character except .)
\. match the character .
Collapse
dechamp profile image
DeChamp Author • Edited

gorgeous! I love me some regex. I was trying to do this yesterday but going about it all wrong. I was trying to abstract out the last part of the domain. Should have made it easy on myself and just find/replace the subdomain! Thank you!

Collapse
elanid profile image
Daniel J Dominguez • Edited

Well, according to the documentation for slice, using a negative index will allow you start indexing from the end of the array rather than the beginning.
So domainParts.slice(domainParts.length - 2, domainParts.length) is equivalent to domainParts.slice(-2).
Another thing is that since admin is a constant, you can add that when you are concatenating the string rather than manipulating the array.

var url = window.location;

// example domain would have a subdomain so https://auth.domain.ext
var domain = url.host;

var subdomain = 'admin';
var mainDomain = domain.split('.').slice(-2).join('.');
var fullAdminDomain = url.protocol + '//' + subdomain + '.' + mainDomain;

Array.prototype.slice

Collapse
dechamp profile image
DeChamp Author

aww yes! nice!