0

Here is the sample of URLs.

1) domain.com/our-work/insights/tips-and-advice/2008/02/04/the-path-to-good-design-is-proper-analytics
2) subdomain.domain.com
3) im.domain.com/About.htm
4) domain.uk/help.htm

Get the Result like this

domain.com
domain.uk
Musakkhir Sayyed
  • 7,012
  • 13
  • 42
  • 65
  • 1
    I think it can be done quite simply using [regex](http://www.w3schools.com/jsref/jsref_obj_regexp.asp). Also, what have you tried so far? – Vivek Pradhan Feb 18 '15 at 09:38

4 Answers4

1

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: (?:[^/:]*:[^/@]*@)?

Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
0

You can get host name by

window.location.hostname

Manual

Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
0

I think this regex (if you want to do with the regex) will do the job:

\w+\.(?=(com|uk))

demo here.

Amen Jlili
  • 1,884
  • 4
  • 28
  • 51
0

try this.

you can achieve this functionality by javascript function.

var name = document.domain;

and you want to find out the domain name from sub-domain than use this.

var parts = location.hostname.split('.');
var subdomain = parts.shift();
var upperleveldomain = parts.join('.');
var sndleveldomain = parts.slice(-2).join('.');
alert(sndleveldomain);
Manish Sharma
  • 2,406
  • 2
  • 16
  • 31