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(str, pos) {
// Sanitise input
str = str + "";
pos = parseInt(pos, 10);
// Snap to a word on the left
if (str[pos] == " ") {
pos = pos - 1;
}
// Handle exceptional cases
if (pos < 0 || pos >= str.length-1 || str[pos] == " ") {
return "";
}
// Build word
var acc = "";
for ( ; pos > 0 && str[pos-1] != " "; pos--) {}
for ( ; pos < str.length && str[pos] != " "; pos++) {
acc += str[pos];
}
return acc;
}
alert(getWordAt("this is a sentence", 6));
Something like this. Be sure to thoroughly test the loop logic; I didn't.