Categories
JavaScript Answers

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

Spread the love

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.

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 *