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});
How do you dynamically detect if there is a subdomain?
@ chux18 – There’s a really good post here @ snipplr.com on detecting a url subdomain.
And what about domain.co.uk ?
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.
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