var getStart = function(index, text){ while(index > 0 && text[index] !== " "){ index--; } return index; } var getEnd = function(index, text){ while(index < text.length && text[index] !== " "){ index++; } return index; } var getSelectedWord = function(firstIndex, lastIndex, text){ return text.substring(getStart(firstIndex, text), getEnd(lastIndex, text)).split(' '); }