-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
  • 17,940
  • 43
  • 142
  • 263
  • 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
  • 195,511
  • 20
  • 184
  • 225
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
  • 666,277
  • 106
  • 705
  • 986