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.

7
  • so what do you want ? Commented Mar 9, 2014 at 9:49
  • do you want the domain name and its extension or just the domain name ? Commented Mar 9, 2014 at 9:49
  • just the domain name for start Commented Mar 9, 2014 at 9:51
  • so in stackoverflow.com, you need stackoverflow? Commented Mar 9, 2014 at 9:51
  • Yes, but remember, there might be stackoverflow.co.uk Commented Mar 9, 2014 at 9:54

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

5 Comments

OP is asking for domain name
? Thank you hello world
Thats what mate. OP is asking for domain name and not www.
when i ran it to cnn.co.uk it doesn't work, despite the fact that it works with cnn.com
@Wind64bit, mine works in that case. So please check out my answer
-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/

4 Comments

@Downvoter, dare to elaborate ? Or just taking revenge?
I am not looking for www but for stackoverflow only
Yes, I know that. It doesn't give www only stackoverflow
Did you even check it out ? @Wind64bit

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.