Categories
JavaScript Answers

How to filter strings in array based on content with JavaScript?

Spread the love

To filter strings in array based on content with JavaScript, we use the filter method.

For instance, we write

const PATTERN = /bedroom/;
const filtered = myArray.filter((str) => {
  return PATTERN.test(str);
});

to call myArray.filter with a callback that calls PATTERN.test to check if str matches the PATTERN regex pattern.

An array with the strings that matches PATTERN is returned.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *