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

339
Visualizações
How to filter out non-numeric characters except ones matching a specific pattern in Javascript?

I have an array containing strings that represent numbers. The only two valid types of elements in the array are:

  1. All-numeric strings (Eg: "123","123344")
  2. Strings that match a specific pattern of xxx-xxxxx where all x are numbers (Eg:"123-12345", "233-30000").

This pattern can be added to more values in the future ie xx-xxxxx and x-xx-xxx where all x are still numbers:

I have the below code which solves 1 but not 2 :

const arr = ["ab's-test#s", "ab-c", "124", "123-12345"];
var arr2 = arr.filter(function(el) {
    return el.length && el==+el && el.match(new RegExp("^\\d{3}(-\\d{5})?$"));
});
console.log(arr2)

This prints out ["124"] However - I want it to print out ["124","123-12345"]

Is there a way I can allow numbers and numeric patterns as a part of the same filter function? Thanks in advance.

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

0

You can use conditional OR with regex to test your string is either number or number with pattern xxx-xxxxx.

const arr = ["ab's-test#s", "ab-c", "124", "123-12345"],
      arr2 = arr.filter((str) => /^\d{3}-\d{5}$/.test(str) || /^\d+$/.test(str));
console.log(arr2)

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use a single pattern placing the or | in the regex itself, using a non capture group (?:....) to match either of the alternatives between the anchors to assert the start and the end of the string:

The updated pattern will become:

^(?:\d{3}-\d{5}|\d+)$

const arr = ["ab's-test#s", "ab-c", "124", "123-12345"];
const arr2 = arr.filter(str => /^(?:\d{3}-\d{5}|\d+)$/.test(str));

console.log(arr2)

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