Skip to content
Advertisement

How to implement a ‘contains’ search in JavaScript

I’m creating a search box that allows you to search for different companies. I’d like the search box to perform a ‘contains’ search. For example, let’s say that I want to look up the company ExxonMobil Oil Corp. Typing in any of the following should include the company in the list of results (this isn’t exhaustive):

  • oil
  • corp
  • oil corp
  • exxonmobil
  • exxonmobil oil
  • exxonmobil oil corp

The words don’t have to be complete, just to be clear. The phrase ‘oil co’, for instance, should still bring up a result.

Typing in ‘exxonmobil corp’, however, will not bring up the company as a result since ‘corp’ does not immediately follow ‘exxonmobil’ in the company’s name.

Is there a go-to method for implementing this type of search, keeping time efficiency in mind? In my case, there can be thousands of companies to search through. And I’d like to be able to display the list of results on the fly as the user is typing into the search box.

I’m aware of the trie data structure, but from what I’ve read, it seems to work best for ‘starts with’ searches. So it wouldn’t match searches like ‘oil corp’, ‘oil’, or ‘corp’ with ExxonMobil Oil Corp. Perhaps there’s a way to tweak the trie to do as I want, but I’m just not sure if that’s the best way to go.

Thank you for the responses. A few of you suggested looking into String.prototype.includes(). I gave that a try, and it does seem to work well with no performance issues.

Advertisement

Answer

100 companies is fast.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement