Search code examples
javascriptregexdns

Javascript/Regex for finding just the root domain name without sub domains


I had a search and found lot's of similar regex examples, but not quite what I need.

I want to be able to pass in the following urls and return the results:

  • www.google.com returns google.com

  • sub.domains.are.cool.google.com returns google.com

  • doesntmatterhowlongasubdomainis.idont.wantit.google.com returns google.com

  • sub.domain.google.com/no/thanks returns google.com

Hope that makes sense :) Thanks in advance!-James


Solution

  • You can't do this with a regular expression because you don't know how many blocks are in the suffix.

    For example google.com has a suffix of com. To get from subdomain.google.com to google.com you'd have to take the last two blocks - one for the suffix and one for google.

    If you apply this logic to subdomain.google.co.uk though you would end up with co.uk.

    You will actually need to look up the suffix from a list like http://publicsuffix.org/