How to get domain/sub-domain/extension from URL in javascript? - Java @ Desk

Friday, July 26, 2013

How to get domain/sub-domain/extension from URL in javascript?

Consider the following URL:
http://www.google.com/
This URL has 3 parts

1) www - subdomain
2) google - domain
3) com - extension

In javascript, use the below code to get the complete URL
document.domain
var tokens = document.domain.split('.');//[www,google,com]
var subdomain = tokens[tokens.length - 3];//www
var domain = tokens[tokens.length - 2];//google
var extension = tokens[tokens.length - 1];//com








1 comment:

  1. Hi, this wont work for domains with subdomains, if you just need to get the domain name of the current page you can use my version of the code that uses a cookie setting technique to get the root domain... http://rossscrivener.co.uk/blog/javascript-get-domain-exclude-subdomain

    ReplyDelete