Get the site name in the javascript url

Asked

Viewed 2,089 times

1

Guys, I got this: I can have the following situations from a url: www.exemplo.com.br or http://exemplo.com.br or http://www.exemplo.com.br and also with HTTPS. I would like to take only the word "example". However I do not know where to start because there can be various situations as you are seeing! How do I do it?

3 answers

5


Try to use:

window.location.hostname

You can take a look at the Location object, which it has several attributes that might be interesting for your solution.

If the url is in a variable, divide the url into an array as it is in the Miguel response.

var url = "www.google.com"
url.split('.')
=> Array [ "www", "google", "com", "br" ]
url.split('.')[1]
=> google
  • How do I use the url in a variable? Example: var url = "www.google.com"?

  • @Thiago updated my answer.

4

Do the following from the domain name (window.location.hostname):

var url = window.location.hostname; // obter o dominio
var url_splt = url.split('.')
var url_name = url_splt[url_splt.length - 2];
alert(url_name);

In case .... .com.br you should do (instead of url_splt[url_splt.length - 2]):

url_splt[url_splt.length - 3]

1

Try it this way:

var splt = window.location.hostname.split('.')
var dominio = (splt[0] === 'www') ? splt[1] : splt[0];
console.log(dominio);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.