I have an array containing strings that represent numbers. The only two valid types of elements in the array are:
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.
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)
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)