Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

83
Vistas
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.

almost 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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.

almost 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda