DEV Community

Discussion on: Daily Challenge #89 - Extract domain name from URL

Collapse
 
zerquix18 profile image
I'm Luis! \^-^/ • Edited

Javascript!

function domainName(domain) {
  const a = document.createElement('a');
  a.href = domain;
  const { hostname } = a;
  const hostSplit = hostname.split('.');
  hostSplit.pop();
  if (hostSplit.length > 1) {
    hostSplit.shift();
  }
  return hostSplit.join();
}

domainName('https://twitter.com/explore') == "twitter"
domainName('https://github.com/thepracticaldev/dev.to') == "github"
domainName('https://www.youtube.com') == "youtube"
Enter fullscreen mode Exit fullscreen mode
Collapse
 
ashawe profile image
Harsh Saglani

Can you please explain what

const { hostname } = a;

does and how?

Collapse
 
ap13p profile image
Afief S

It has the same effect as:
const hostname = a.hostname

Collapse
 
midasxiv profile image
Midas/XIV

That's called destructuring assignment. "a" probably is an object which has the hostname property so that assignment extracts hostname.
I'm just writin about this 😅. Hopefully that'll help you.