JDO JDO - 5 months ago 8
Javascript Question

How get domain from string?

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


If
string
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

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;
}

console.log(getHostname("https://example.com/app/something"));
console.log(getHostname("example.com/app/something"));

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.