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

Sometimes, we want to filter strings in array based on content with JavaScript.

In this article, we’ll look at how to filter strings in array based on content with JavaScript.

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

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

For instance, we write:

const myArray = ["bedroomone", "bedroomonetwo", "bathroom"];
const pattern = /bedroom/;
const filtered = myArray.filter((str) => {
  return pattern.test(str);
});
console.log(filtered)

We call myArray.filter with a callback that matches all the strings that has 'bedroom' in it by calling pattern.test with str.

Therefore, filtered is ['bedroomone', 'bedroomonetwo'].

Conclusion

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