To do that you can simply use the String.prototype.split()
method with /
as delimiter to extract the hostname and then you take the end of the hostname (that contains a dot) with String.prototype.match()
:
var m = url.split('/')[0].match(/[^.]+\.[^.]+$/);
if (m)
var domain = m[0];
Note: if the url begins with a scheme you need to remove it before:
var pat = '^https?://';
url = url.replace(new RegExp(pat, 'i'), '');
An other way consists to find the domain directly:
var pat = '^(?:https?://)?(?:[^/:]*:[^/@]*@)?[^/]*([^./]+\\.[^./]+)';
var m = url.match(new RegExp(pat, 'i'));
if (m)
var domain = m[1];
But in this case, you need to deal with a possible login/pass part before the hostname. This is the reason of this subpattern: (?:[^/:]*:[^/@]*@)?