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

144
Vistas
Regex replace not working when trying to replace a string - JS

I have a bunch of common regex patterns which I got from here. I try applying them to a string but they do not seem to modify anything. It just returns me the same value. Can you please enlighten me on what I am doing wrong.

const str = 'sadas87676szdhgzshdgszhjg,##%$,.%';

const commonRegexPatterns = {
  DIGITS: /^[0-9]+$/,
  ALPHABETIC: /^[a-zA-Z]+$/,
  ALPHANUMERIC: /^[a-zA-Z0-9]+$/,
  DATE: /^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.](19|20)?[0-9]{2}$/,
  EMAIL: /^[a-zA-Z0-9._%-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/,
  ZIP: /^[0-9]{5}(?:-[0-9]{4})?$/,
  DIGITSWITHCOMMA: /^[\d,]/,
  DIGITSWITHCOMMAPERCENTAGE: /^[\d,%]/,
}

console.log('DIGITS', str.replace(commonRegexPatterns.DIGITS, ''));
console.log('ALPHABETIC', str.replace(commonRegexPatterns.ALPHABETIC, ''));
console.log('ALPHANUMERIC', str.replace(commonRegexPatterns.ALPHANUMERIC, ''));
console.log('DIGITSWITHCOMMA', str.replace(commonRegexPatterns.DIGITSWITHCOMMA, ''));
console.log('DIGITSWITHCOMMAPERCENTAGE', str.replace(commonRegexPatterns.DIGITSWITHCOMMAPERCENTAGE, ''));
console.log('ZIP', str.replace(commonRegexPatterns.ZIP, ''));

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Well, your regex patterns are wrong. Ok, not really "wrong", but they are not what you seem to want. For example, DIGITS:

^[0-9]+$

This pattern has anchors (the ^ is the start of the string, the $ is the end). It will match an entire string of numbers, but not just any number inside a string. For your purpose, you want it without the anchors, like:

[0-9]+

The same applies to most of the other patterns in your snippet. Remove the anchors if you are just trying to match part of a string. Additionally, since you seem to be trying to remove all occurrences of patterns in the string, you probably want to use the g flag in your patterns. For example, ALPHABETIC (without the anchors):

/[a-zA-Z]+/

This will match the first group of letters in your string, but not the ones after it. If instead you use

/[a-zA-Z]+/g

You will be able to replace every match.

about 4 years ago · Santiago Trujillo 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