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

231
Visualizações
Js Regex only allowed characters one occurence

Trying the regex very hard but could not get the desired result.

  1. Must begin with numbers and maximum of 4
  2. followed by only one allowed alphabet

Please have a look at below code.

var strings = [
 '1h', //should match
 '13s', //should match
 '30m', //should match
 '42hr', //should not match
 '8   hours  ', //should not match
 '765765', //should not match
 '5sec', //should not match
 '23445345345s', //should not match
 '335m' //should match
];

for (var i = 0; i < strings.length; i++) 
{
    var match = strings[i].match(/\d{4}[h|m|s]{1}/g);
  console.log(strings[i], (match ? "Match" : "Not match"));
}

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

0

You regex should be:

/^\d{1,4}[hms]$/gm

First, you require 4 digits with d{4}

Change it to d{1,4} to be one to four digits

Then add a $ to indicate the end of the string, so it doesn't allow more characters after the letter

Check out Regex101, Really useful for testing and understanding regex

about 4 years ago · Juan Pablo Isaza Relatório

0

I've added a ^ to match from start

strings.filter(x =>  x.match(/^\d{1,4}[hms](?!\w)/g)  )
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