Ok, this is a multipart concept. However I’m sure if I can figure this piece out, the rest will follow.
What I have is an array of Words and Phrases. And I have a TextArea where people can type in. What I want to do is be able to search the array for matches or similarities in what the user is typing. The closest thing I can think of is an auto complete function. But thats not entirely what I want, yes in part what I want is an auto completes functionality, but so much more in the end run that an existing auto complete is a bit bulky for my needs.
What my Aim is, is after the user hits the spacebar is to trigger the search as they type. Now up to this point I am good. My issue is my logic is flawed from here. I want to be able to take the entire boy of text up to the point of hitting the spacebar and check it against my array of words and phrases. But Im not sure how. Currently I am split() on the textarea itself where space is my split() delimiter, but I realize now that thats not right. What I was thinking initially was split it, check it against the other array and it would be a happy day if something matched, then I realized I have phrases, if I am trying to check a phrase for a match then I wont match one.
Well hopefully this makes sense. I need to walk through logic on this, there really isnt code currently, as I am not debugging, I am trying to figure out a logic to work with that works. So I can move forward.
UPDATE:
Check this fiddle: http://jsfiddle.net/VwNHN/
You will need to tweak it to your requirements, but it will give a fair idea of how the below logic can be implemented.
Well, the logic upon keypress (probably any key and not just spacebar) can be something like:
1) Get your current cursor position – say
XRefer for example: http://demo.vishalon.net/getset.htm
2) Get
Ncharacters to the left ofX. i.e. a substring of the whole text from indexX-NtoX– store it inY. You will need to fix on a value forN(for ex: 100).Nis the longest word/phrase you are looking to match.ex: if full text is
"hello world i am a sentence", and cursor is at the end, andNis10,Ywould be"a sentence"3) Split
Yby space character and store each split in an array incrementally and then reverse it – lets call the arrayPHRASESex: if
Yis"this is a sentence"– thenPHRASESwould be4) Check your array of words/phrases with each item in the
PHRASES– the longest matching parts will come first and the short matching ones will come last – this set of matches is your auto-complete list.