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

120
Visualizações
Custom URL validation using Javascript RegExp

I created a function that should check if a string correspond to an url format:

const test = (str) => {
  const t = new RegExp(
    '^(https?:\\/\\/)?' + 
      '(www\\.)' + 
      '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|)' + 
      '(\\#[-a-z\\d_]*)?$', 
    'i',
  );

  return t.test(str);
};

console.log(test('http://demo.com')); //expect true
console.log(test('http://ww.demo.com')); //expect false

For each console.log() i wrote the expected value, in both cases i got false. In the last case false is ok, but in the first i should get true. How to fix the regex?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Even if this answer is a bit too much for this Problem, it illustrates the problem: Even if it might be possible to create a regexp to check the url, it is much simpler and more robust to parse the URL and "create a real Object", on/with which the overall test can be decomposed to a number of smaller tests.

So probably the builtin URL constructor of modern browsers may help you here (link1, link 2).

One approach to test you url might look like this:

function testURL (urlstring) {
var errors = [];
try {
    var url = new URL(urlstring);

    if (!/https/.test(url.protocol)) {
       errors.push('wrong protocol');
    }

    //more tests here

} catch(err) {
  //something went really wrong
  //log the error here

} finally {
  return errors;
}
 }if (testURL('mr.bean').length == 0) { runSomething(); }
about 4 years ago · Juan Pablo Isaza 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