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

Viewed 14404

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

5 Answers

Without testing the validity of top level domain, I'm using an adaptation of stormsweeper's solution:

domain = 'sub.domains.are.cool.google.com'

s = domain.split('.')

tld = s.slice(-2..-1).join('.')

EDIT: Be careful of issues with three part TLDs like domain.co.uk.

Related