AnApprentice
AnApprentice

Reputation: 110990

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

Given 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 from the string just cnn.com for all of them? Top level domain plus extension?

Thanks

Upvotes: 5

Views: 3762

Answers (5)

chrishawn
chrishawn

Reputation: 578

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

    matches = urls.exec(input);

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

    return output;
}

Upvotes: 1

Gubatron
Gubatron

Reputation: 6479

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

Upvotes: -1

Alex
Alex

Reputation: 35407

​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

Upvotes: 3

tkone
tkone

Reputation: 22728

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

If you want it reassembled:

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

But this won't work with co.uk or something. There's no hard nor fast rule for this, not even regex will determine that.

Upvotes: 0

Dagg Nabbit
Dagg Nabbit

Reputation: 76736

Given that there are top-level domains with dots in them, for example "co.uk", there's no way to do this programatically unless you include a list of all of the TLDs with dots in them.

Upvotes: 0

Related Questions