I have created a search mechanism that searches through an array of strings for an exact string match, however I want it to be a bit more intuitive.
I can also get it to search for a string within the string (for example chicken
in grilled chicken
- however the issue is this allows users to type ken
or ill
and it returns grilled chicken
.
I would like it to return if I typed in chicken
or grilled
.
Does anyone have any suggestions on how to have a more intuitive search mechanism?
EDIT:
The correct answer below worked when typing 1 word and it would search all individual words in a string. However, I realised it fails when you search with 2 words (as it only searches each string word individually).
I solved this by adding || search == string
to the if
to include not just individually word matches but whole string matches.
However I am still having an issue with it either searching for:
Whole string matches OR Matches with individual words.
This means it fails when search = green cup
and string = big green cup
. Is there a way to solve this by cutting for collections to search within? Perhaps something similar to:
string.split(' ')
but to also include big green, green cup
to the array also?