0

I'd like to know if it is possible to get the name of a site using javascript.

For example, if I'd like to get the main URL of a web-site, I will use

window.location.hostname

and the script will returns let's say "stackoverflow.com"

Now what about if I'd like the script to return only the name of a website, in this case "stackoverflow"? (stackoverflow.com --> stackoverflow; facebook.com --> facebook and so on, in other word, I would like to remove the first domain from the url)

Thanks!

luaLover
  • 141
  • 1
  • 11

3 Answers3

0

You could do:

window.location.hostname.split('.').slice(0,-1).join('.')

Which splits the hostname into an array by .'s

["stackoverflow", "com"]

remove's the last element from the array

["stackoverflow"]

and then joins the array back together.

I do it this way in case you have a url like 'dev.yoursite.com' you would get 'dev.yoursite'

dave
  • 62,300
  • 5
  • 72
  • 93
0

I would do regexp. But its a little ugly:

location.hostname.replace(/^(www.|)([\w]+)(\..+|)/g, "$2")
josephnvu
  • 1,210
  • 1
  • 9
  • 14
0

For the way your question is made, looks like you are trying to archive this in a single line javascript function.
Then i'm afaid, there's no an easy way to do it...

Many examples would suggest to split by dot, but then, will only work for a host name with a first-level & second-level domain names.

When the host name gets more complex.. those solutions normally will fail.
ex.

  • subdomains (mail.example.com)
  • composed domains (.co.uk)
  • and so on...

Can give you a few examples to read and find out which one fit your needs.

So in brief..
If you want a single line, easy to do and magic line to do that...
The answer is no, it's not possible (single solution that works in all cases).

But, if you like to learn, try, read and inform about it... then yes.. Absolutely
It's more complicated, but can be done.

So, please provide a more elaborate question, with examples and what you tried so far to solve it, and we will happy to help with more elaborate answers.

Community
  • 1
  • 1
gmo
  • 8,860
  • 3
  • 40
  • 51
  • Thanks for the links you've posted. Anyway this question was posted for curiosity purposes only. I'll take a look at the guides and example you've linked. Thanks again – luaLover Jun 20 '14 at 00:39
  • Great then! I'm glad the info and the links helps you to learn more about it or at least to understand better how it works. – gmo Jun 20 '14 at 12:09