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
1
  • 1
    I think it can be done quite simply using regex. Also, what have you tried so far? Commented Feb 18, 2015 at 9:38

4 Answers 4

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

3
  • it doesn't gives the expected result. Commented Feb 18, 2015 at 9:50
  • @Musakkhir: exact, I have readen the question too quickly! Is there always only one dot in the domain name? Commented Feb 18, 2015 at 9:57
  • There will be always one dot in domain name, above pattern is not working for those urls. Commented Feb 18, 2015 at 10:07
0

You can get host name by

window.location.hostname

Manual

1
  • 1
    The OP wants to get the hostname of the url strings, not the page's url. Vivek's solution is correct. Commented Feb 18, 2015 at 9:39
0

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

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

demo here.

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);
4
  • The above urls are in string. Commented Feb 18, 2015 at 10:13
  • so in which datatype you want? Commented Feb 18, 2015 at 10:16
  • The location.hostname works with only current domain. I want the expected results from all urls which is in string form. Commented Feb 18, 2015 at 10:18
  • so what the problem u faced in this ans? Commented Feb 18, 2015 at 10:20

Not the answer you're looking for? Browse other questions tagged or ask your own question.