Given a URL as a string, how to extract only the domain and extension?

Specify a string with URLs in the following formats:

https://www.cnn.com/
http://www.cnn.com/
http://www.cnn.com/2012/02/16/world/american-nicaragua-prison/index.html
http://edition.cnn.com/?hpt=ed_Intl

W JS / jQuery, how can I extract only cnn.com from a string for all of them? Top level domain plus extension?

thank

+5
source share
5 answers
var loc = document.createElement('a');

loc.href = 'http://www.cnn.com/2012/02/16/world/index.html';
window.alert(loc.hostname);​ // alerts "cnn.com"

Credits for the previous method:

Creating a new Location object in javascript

+3
source
var domain = location.host.split('.').slice(-2);

If you want it to be reassembled:

var domain = location.host.split('.').slice(-2).join('.');

But that will not work with co.uk or anything else. There is no hard or fast rule for this; even a regular expression will not determine this.

0
source

, , "co.uk", , TLD .

0
function domain(input){
    var matches,
        output = "",
        urls = /\w+:\/\/([\w|\.]+)/;

    matches = urls.exec(input);

    if(matches !== null){
        output = matches[1];
    }

    return output;
}
0
// something.domain.com -> domain.com
function getDomain() {
  return window.location.hostname.replace(/([a-z]+.)/,"");
}
-1

All Articles