For string input of \'this is a sentence\' it must return \'is\' when position is 6 or 7. When position is 0, 1, 2, 3 or 4 result must be \'this\'.
What is the easie
function getWordAt(s, pos) {
// make pos point to a character of the word
while (s[pos] == " ") pos--;
// find the space before that word
// (add 1 to be at the begining of that word)
// (note that it works even if there is no space before that word)
pos = s.lastIndexOf(" ", pos) + 1;
// find the end of the word
var end = s.indexOf(" ", pos);
if (end == -1) end = s.length; // set to length if it was the last word
// return the result
return s.substring(pos, end);
}
getWordAt("this is a sentence", 4);