Jason Knight
1 min readDec 27, 2022

--

Interesting seeing all the different approaches, but I think what's really at issue here is you're using the wrong terminology. This is why when {expletive omitted} say "just google it" I have to choke back the urge to strangle someone. If you don't know what it's called of course your results are going to be ... less than desirable.

Because you're looking for the "second level domain" or SLD, NOT the "domain" or "domain name"

www == subdomain (optional)

google == second level domain / SLD

com == top level domain / TLD

This is the type of thing that if you need it once in a project, you probably need the other pieces too. These days to accomplish that I'd extend the URL object to include those using Object.defineProperty on URL.prototype for an outer object, with the properties { sub, second, top }. The outer object property getting a double underscore for namespace safety (borrowing from LoDash)

Try this on for size:

https://codepen.io/jason-knight/pen/qBybREX

I set up result caching on it as well as a few other things that if you call it a lot results in "quality of life" improvements. An ideal implementation would probably use setters and getters to make manipulating the pieces of the URL easier.

--

--

Jason Knight
Jason Knight

Written by Jason Knight

Accessibility and Efficiency Consultant, Web Developer, Musician, and just general pain in the arse

No responses yet