2

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?

4
  • 2
    "/_\d+/g" -> /_\d+/g you're passing a string instead of a regex. EDIT: also you cannot use a regex in .inclues, you need to do regex.test(string). Commented Jun 1, 2021 at 12:27
  • 1
    That ain't a reg exp, that be a string and includes does not use a reg exp. Commented Jun 1, 2021 at 12:27
  • Oh, got it! Thanks folks! Commented Jun 1, 2021 at 12:35
  • If my answer did not solve your problem please consider updating the question. Commented Nov 28, 2021 at 19:18

2 Answers 2

2

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+$/.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.