Get the site name in url in javascript

0

Well, I have the following: I can have the following situations from a url: www.example.com or link or link and also with HTTPS. I would like to take only the word "example". But I do not know where to start because you can have several situations as you see! How do I do this?

    
asked by anonymous 23.02.2017 / 19:34

3 answers

3

Try to use:

window.location.hostname

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

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

var url = "www.google.com.br"
url.split('.')
=> Array [ "www", "google", "com", "br" ]
url.split('.')[1]
=> google
    
23.02.2017 / 19:39
3

Does 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 the case of .... .com.br you should do (instead of url_splt[url_splt.length - 2] ):

url_splt[url_splt.length - 3]
    
23.02.2017 / 19:42
1

Try this:

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