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

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

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 Denunciar

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