JDO JDO - 1 year ago 72
Javascript Question

How get domain from string?

var string = "https://example.com/app/something";
var string = "example.com/app/something";
new URL(string.origin)

have protocol all ok, and if not. have error Failed to construct 'URL': Invalid URL(…)

How can I obtain the root domain without using regex?

Answer Source

The question is still a bit unclear, and I'm not entirely sure how you're getting that string, but just for the sake of argument, here's a quick solution:

function getHostname(str)
  str = (/^\w+:\/\//.test(str) ? "" : "http://") + str
  return new URL(str).hostname;


Yes, technically, this technically does use a regular expression to check if the protocol is present, but it uses the URL class actually parse the host name.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download