Skip to content
Advertisement

Search function .match() case sensitive

this.items is an array of objects. I am using this to search the items by the search bar, but .match() is case sensitive. For example, if I have an item called Milk, when I type milk, it won’t come up.

How can I make this work for both lowercase and uppercase? Live demo

filteredOffers() {
    return this.items.filter((offer) => {
        return offer.title.match(this.search);
    });
},

I tried:

offer.title.match(/this.search/i);

but it gives me a blank page.

Advertisement

Answer

Convert the two terms to lowercase before comparing them:

export default {
  computed: {
    filteredOffers() {
      const searchTerm = this.search.toLowerCase();
      return this.items.filter((offer) => {
        return offer.title.toLowerCase().match(searchTerm);
      });
    }
  }
}

const items = [
  { title: 'Foo bar' },
  { title: 'The Milk Is Delicious' },
  { title: 'Baz qux' },
  { title: 'I drink chocolate milk' },
]

const search = 'milk'
const searchTerm = search.toLowerCase()
const result = items.filter((offer) => {
  return offer.title.toLowerCase().match(searchTerm)
})

console.log(result)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement