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

411
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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