0

Is there a way to get only the domain name from a given string.

Lets say the string is:

var url = "https://subdimain.thedomain.com/this/path/file.html"

All I want to get is:

thedomain.com

however, there are many factors I am not sure how to account for. For example:

  • https or http
  • subdomain or none
  • tld (.com/.co.uk/.in/.fr) etc....
  • path etc.. (/this/path/file.html)

Thanks for your help :)

JamesG
  • 1,353
  • 5
  • 31
  • 76

1 Answers1

-2

Here's an easy way:

function domain(url){
  var a = document.createElement('a');
  a.href = url;
  var s = a.hostname.split('.'), d = s.length-2;
  return s[d]+'.'+s[d+1];
}
var sub = domain('https://subdimain.thedomain.com/this/path/file.html');
console.log(sub);
StackSlave
  • 10,436
  • 2
  • 17
  • 33