0

I was working on how to find a URL's domain, and thanks to my previous question, I came to this answer:

var domain = (location.host)
        var arr=domain.split(".")
        extension=arr[arr.length-1]

        if(extension=="cnn")
            alert("true");

However, I have 2 problems:

  • It works fine untill you come across to a site with extension co.uk.
  • Is there a way to count . from the start and not from the end?

For example, for the website www.cnn.com, it'd start counting from the www, and not from the com.

Community
  • 1
  • 1
Wind64bit
  • 7
  • 3

2 Answers2

0

Okay, here's the edit to make you understand how it works.

Say, your website is "www.cnn.co.uk". If you understand array, this line would return you the array of 4 elements delimited by '.'

var arr=domain.split(".")

i.e. [www, cnn, co, uk];

Now it's really upto you what element you want out of this array. If you know the element name, and you want to retrieve cnn, you can do

`extension = arr[1];`

You can also iterate over an array to get each element.


extension = arr[0];

it will return you www.

Pankaj Gadge
  • 2,748
  • 3
  • 18
  • 25
-1

Use this function:

function GetDomainName() {
    if (location.host.split('.')[0] == 'www') {
        return location.host.split('.')[1];
    } else {
        return location.host.split('.')[0];
    }
}

Call it like this:

var domainName=GetDomainName();

But remember, this will not work in subdomains like

programmers.stackexchange.com

Demo: http://jsfiddle.net/j7VP6/

Amit Joki
  • 58,320
  • 7
  • 77
  • 95