Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

338
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!