Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

82
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda