1

In my project, I have many strings containing domain names and subdomain name in various formats.

I need a JavaScript function that returns to me just the first level domain name in string, for example:

string: https://www.example.com/test/intro.php
return: www.example.com

string: http://www.test.fr/
return: www.test.fr

string: http://mysite.eu/portal/
return: mysite.eu

[...]

Does there exist a function that achieves this goal in every case?

Amal Murali
  • 75,622
  • 18
  • 128
  • 150
AleMal
  • 1,977
  • 6
  • 24
  • 49

4 Answers4

3

Create anchor element and make href the string.

var a  = document.createElement('a');
a.href = data;

Get the hostname from it.

a.hostname

Similarly you can fetch protocol and other properties as well.

a.protocol; // => "http:"
a.host;     // => "example.com:5000"
a.hostname; // => "example.com"
a.port;     // => "5000"
a.pathname; // => "/pathname/"
a.hash;     // => "#value"
a.search;   // => "?q=test"

Here's the function to answer your question

function getDomainFromURL(data) {
     var a = document.createElement('a');
     a.href = data;
     return a.hostname;
}
Sorter
  • 9,704
  • 6
  • 64
  • 74
  • I like this, it's outside the box but how cross-browser is it? [According to MDN](https://developer.mozilla.org/en-US/docs/Web/API/URLUtils.hostname) there's not a lot of support but I don't know how out of date that is because it works fine on my Chrome. – Emissary Dec 02 '13 at 12:52
  • you need to provide a complete url string, relative urls wont work. And it works fine in ie as well. just tested in ie 9. I've been using it since a while. – Sorter Dec 02 '13 at 12:59
  • brilliant, concise and comprehensive answer, thanks! – user1063287 Jul 04 '14 at 17:27
  • update: i have just come across the behavior in ff console where if there is no `www` prefix in `data` (using the variable in the example above) then `a.hostname` etc will not return the desired string, rather it will return the current window's hostname. – user1063287 Jul 04 '14 at 18:45
0

Yes, you can use document.location.hostname or document.location.host.

edit Aaah, I understand now.

Check this link: http://james.padolsey.com/javascript/parsing-urls-with-the-dom/

function parseURL(url) {
    var a =  document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':',''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function(){
            var ret = {},
                seg = a.search.replace(/^\?/,'').split('&'),
                len = seg.length, i = 0, s;
            for (;i<len;i++) {
                if (!seg[i]) { continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
        hash: a.hash.replace('#',''),
        path: a.pathname.replace(/^([^\/])/,'/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
        segments: a.pathname.replace(/^\//,'').split('/')
    };
}

Then all you do is:

var url = "http://domain.com/blah/";
var urlObj = parseUrl(url);
var host = urlObj.host;
nl-x
  • 11,762
  • 7
  • 33
  • 61
0

There is no built in function, but you can make your own.

This regexp matches all the cases you posted:

/:\/\/(.*?)\//

http://regex101.com/r/dS8uK8

Usage:

var str = 'http://mysite.eu/portal/';
var domain = str.match(/:\/\/(.*?)\//)[1];
console.log(domain); //"mysite.eu"
Tibos
  • 27,507
  • 4
  • 50
  • 64
0

If you don't like regexp (like me :) ) you can try this:

function getDomain (inputString) {
  var res = inputString.split("/");
  return res[2];
}
Andrew Surzhynskyi
  • 2,726
  • 1
  • 22
  • 32