Reputation: 33
I am not very well versed with coding. I have a set of strings in an array and I am trying to filter them out using regex but it's not working for me. I want my result array to return any string containing _number like _0, _01, _000
and the filter that I am using is
var myArray = ["bedroom_01", "bedroom_02", "bedroom" , "bathroom_01"];
var result = myArray.filter(name => name.includes("/_\d+/g"));
console.log(result);
The above code is returning me a blank array. Please let me know what am I doing wrong?
Upvotes: 2
Views: 635
Reputation: 6367
What you are passing to includes is a string not a regexp and includes takes a string not a regexp instead you can use the match
method
var myArray = ["bedroom_01", "bedroom_02", "bedroom" , "bathroom_01"];
var result = myArray.filter(name => name.match(/_\d+/));
console.log(result);
Upvotes: 0
Reputation: 626802
You need RegExp#test
with a regex literal:
var myArray = ["bedroom_01", "bedroom_02", "bedroom" , "bathroom_01"];
console.log(
myArray.filter(name => /_\d+/.test(name))
)
If you need to check if the array item ends with _
+ digits, use /_\d+$/
.
Upvotes: 2