简体   繁体   中英

Hostname to valid URL in javascript

Is there an elegant way to convert a hostname/domain into a valid http url like so:
example.com to https://example.com ?

My current approach is something like:

const domainToURL = (domain: string) => {
  if (!domain.startsWith('http')) domain= `https://${domain}`;
  return new URL('/', domain).origin;
};

I'm sure there is something more robust out there.

This is what I use: Create a dummy URL object, change the .hostname property, then read the.href property . Like this:

 function hostnameToURL(hostname) { // the inital value of the URL object can be anything const url = new URL("https://example.com"); url.hostname = hostname; return url.href; } console.log(hostnameToURL("google.com")); console.log(hostnameToURL("a.fun.website.com")); console.log(hostnameToURL("example.com"));

If you need to take in more parameters (like specifying HTTP or HTTPS), you can easily tweak the function to do so. I find this approach better because you hand off all the work to the browser.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM