How to extract the host from a URL in JavaScript?

javascript, node.js, parsing, url

Solution

I reccomend using the new URL class that is now included in most browsers.

var urls = [
  'http://example.com:3000',
  'http://example.com?pass=gas',
  'http://example.com/',
  'http://example.com'
];

urls.forEach(url => {
  const u = new URL(url)
  console.log(u.hostname)
})

Problem

Capture the domain till the ending characters `$, \?, /, :`. I need a regex that captures `example.com` in all of these. ``` example.com:3000 example.com?pass=gas example.com/ example.com ```

Original source