更新:
Check this fiddle: http://jsfiddle.net/VwNHN/
要件に合わせて調整する必要がありますが、以下のロジックをどのように実装できるかについては正当な考え方があります。
キーの押下時のロジック(おそらくスペースバーだけでなくキーも)は次のようなものです。
1) Get your current cursor position - say X
Refer for example: http://demo.vishalon.net/getset.htm
2) X
の左にある N
文字を取得します。すなわち、インデックス X-N
から X
までのテキスト全体の部分文字列を Y
に格納します。 N
(たとえば100)の値を修正する必要があります。 N
はあなたが探している最長の語句です。
ex: if full text is "hello world i am a sentence"
, and cursor is at the end, and N
is 10
, Y
would be "a sentence"
3) Split Y
by space character and store each split in an array incrementally and then reverse it - lets call the array PHRASES
例: Y
が "これが文章"
の場合 - PHRASES
[ "this is a sentence", "this is a", "this is", "this" ]
4) PHRASES
の各項目を使用して、単語/フレーズの配列を確認します。最長の一致部分が先になり、短い一致する部分が最後に来ます。