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

143
Visualizações
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 Respostas
Responde à pergunta

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