koque
koque

Reputation: 2256

Regex to match sub string of a string

I need to construct a regular expression to match a given value to the brand field of my product array. For instance, given the parameter "am", an array of the following products would be returned: [Amana, Mama, etc]. How do I complete this function?

public searchProduct(term) {
   this.products.forEach(product => {
     if (product.brand.match(`${term}`)) {
       console.log('mtch found', product.brand)
     }

   });
   return of(this.products)
 }

Upvotes: 0

Views: 41

Answers (1)

edkeveked
edkeveked

Reputation: 18371

Unless you have some special reasons to use regex, you can use filter and includes to return only items of your array containing your substring

public searchProduct(term) {
  return this.products.filter(x => x.brand.includes(term))
 }

Upvotes: 2

Related Questions