Interactive by Nature

Remove Subdomain From URL With JavaScript

To remove a subdomain from the current URL in the browser is easier than you think. In my situation, I need to remove the mobile subdomian so that I can set a cookie that can be used on both versions of the website domain. i.e. mobile.sample.com and www.sample.com. I could have hardcoded the domain, but when you’re working with test and dev environments, it’s better to make it dynamic. Here’s what I came up with:

var separate = window.location.split('.');
separate.shift();
var currentdomain = separate.join('.');

The .split() method separates the url into an array of substrings, using the dot as the separator. http://mobile ‘.’ sample ‘.’ com

var separate = window.location.split('.');

Use the shift() method to remove the first element in the url array. In this example, it’s ‘http://mobile’.

separate.shift();

Here, I’m setting the variable currentdomain to equal the result of re-joining the remainder of the url array elements using the .join() method.

var currentdomain = separate.join('.');

Now I can use the jQuery cookie plugin to set a cookie that can be used on both versions of the website.

$.cookie('mobile', 'true', {path: '/', domain: currentdomain});

Comments

  1. How do you dynamically detect if there is a subdomain?

    Chux18 on June, 6th, 2011 at 9:39 pm
  2. @ chux18 – There’s a really good post here @ snipplr.com on detecting a url subdomain.

    admin on June, 7th, 2011 at 7:32 am
  3. And what about domain.co.uk ?

    Kousha on September, 28th, 2012 at 8:23 am
  4. Touché Kousha, I didn’t consider that scenario. This was specific to the problem I was having. If you find something please mention it in the comments.

    admin on September, 28th, 2012 at 2:35 pm
  5. Hey, so obviously if there is no subdomain and you have a .co.uk this function would just return “co.uk”. If you need the domain name from the current url, you can use my technique using a cookie setting method at… http://rossscrivener.co.uk/blog/javascript-get-domain-exclude-subdomain

    Ross Scrivener on June, 16th, 2014 at 8:46 am

Leave a Comment