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

404
Visualizações
Javascript Regex - replacing characters based on regex rules

I am trying to remove illegal characters from a user input on a browser input field.

const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
 console.log('success',myInput)
} else {
  console.log("fail",myInput.replace(???, ""))
}

I can test with the right regex and it works just fine. Now I am trying to remove the illegal characters. The rules are, only lower case alpha character in the first position. All remaining positions can only have lower case alpha and numbers 0-9. No spaces or special characters. I am not sure what pattern to use on the replace line.

Thanks for any help you can provide.

Brad

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

0

You could try the below code:

const myInput = '46432e66Sc'
var myPattern = new RegExp(/^[a-z][a-z0-9]*/);
var test = myPattern.test(myInput);
if (test === true) {
  console.log('success',myInput)
} else {
  console.log("fail",myInput.replace(/[^a-z0-9]/g, ""))
}

Replace is using the following regexp: /[^a-z0-9]/g. This matches all characters that are not lowercase or numeric.

You can validate your regexp and get help from cheatsheet on the following page: https://regexr.com/

about 4 years ago · Juan Pablo Isaza Relatório

0

You could handle this by first stripping off any leading characters which would cause the input to fail. Then do a second cleanup on the remaining characters:

var inputs = ['abc123', '46432e66Sc'];
inputs.forEach(i => console.log(i + " => " + i.replace(/^[^a-z]+/, "")
                                              .replace(/[^a-z0-9]+/g, "")));

Note that after we have stripped off as many characters as necessary for the input to start with a lowercase, the replacement to remove non lowercase/non digits won't affect that first character, so we can just do a blanket replacement on the entire string.

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