-1

Is there a lazy way to get a variable for "top level" host without resorting to if()?

  • example.com: return example.com,
  • cabbages.example.com: return example.com,
  • carrots.example.com: return example.com,
  • otherexample.com: return otherexample.com,
  • cabbages.otherexample.com: return otherexample.com,
  • carots.otherexample.com: return otherexample.com,
Doug Fir
  • 19,971
  • 47
  • 169
  • 299
  • 1
    You could try [regular expressions](http://eloquentjavascript.net/09_regexp.html) or [String.prototype.split](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/split) – nils Nov 03 '15 at 16:51
  • 2
    What about `cabbages.example.co.uk`? Doing this right requires knowing the naming conventions for each top-level domain. – Barmar Nov 03 '15 at 17:01

2 Answers2

0

With the test cases that you provided, one way is to use use split, splice, and join.

window.location.hostname.split(".").splice(-2,2).join(".")

Plenty of ways to write a regular expression, but one is

window.location.hostname.match(/[^\.]+\.[^\.]+$/)
epascarello
  • 204,599
  • 20
  • 195
  • 236
0

You can use a regular expression to get the part of the string that you want:

url = url.replace(/^.*?([^\.]+\.[^\.]+)$/, '$1');

Demo:

var urls = [
  'example.com',
  'cabbages.example.com',
  'carrots.example.com',
  'otherexample.com',
  'cabbages.otherexample.com',
  'carots.otherexample.com'
];

for (var i = 0; i < urls.length; i++) {
  var url = urls[i].replace(/^.*?([^\.]+\.[^\.]+)$/, '$1');
  console.log(url);
}
Guffa
  • 687,336
  • 108
  • 737
  • 1,005