JDO JDO - 9 months ago 20
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?


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.