I've shared two examples here.
But first, lets see the syntax.
filter() method syntax
filter (callback_function, thisValue)
callback_function: A function to run for each array value (or element).
theValue: The value passed to the callback function.
RegExp object syntax
RegExp (pattern, modifiers)
Examples.
🚀 Example 1
In this example, I have three elements. All are string elements. I want to filter out elements that has the characters "ag". I don't care if the characters are in upper case or lower case.
<script> const arrBirds = ["Mourning Dove", "Bald Eagle", 'Eurasian Collared-Dove']; // Create a regex object (a constructor). let regex = new RegExp('ag', 'i'); // get elements (values) that has "ag". // Tests for a match. let filtered = arrBirds.filter(item => regex.test(item)); console.log(filtered); // Output: Bald Eagle </script>
First I have declared a constructor of RegExp.
The RegExp has two arguments.
1) The pattern to search. It will filter values (or elements) that has the characters "ag".
2) The modifier "i": The "i" modifier performs a case-insensitive matching. So it doesn't matter if the characters are in upper case or lower case.
The .filter() method creates a new array from arrBirds(), only after filtering out elements that match the pattern I have provided to the RegExp.
The regex uses the test() method (regex.test(item)) to test for a match in the element. If it finds a match, it will "true", else "false".
🚀 Example 2
I have an array of numbers and string values. I want to filter out only the number elements using filter() and RegExp object.
<script> const arr1 = [350, 'north', 99, 'south']; let regex = new RegExp(/^\d+$/); // get only numeric values. let filtered = arr1.filter(v => regex.test(v)); console.log(filtered); // Output: [350,99] </script>
Note: It will not filter -ve (negative) numbers.
Now lets do the opposite. We will filter out elements that have "alphabets" only.
<script> const arr1 = [350, 'north', 99, 'south']; let regex = new RegExp(/^\D+$/); // get only alphabets values. let filtered = arr1.filter(v => regex.test(v)); console.log(filtered); // Output: [north,south] </script>