function getWordAt (str, pos) {
str = String(str);
pos = Number(pos) >>> 0;
var left = str.slice(0, pos + 1).search(/\S+$/),
right = str.slice(pos).search(/\s/);
if (right < 0) {
return str.slice(left);
}
return str.slice(left, right + pos);
}
This function accepts any space character as a word separator, including spaces, tabs, and newlines. Essentially, this looks like:
- To start a word corresponding
/\S+$/
- Ending the word using
/\s/
, ""
, ; . , , /\S+$/
/\S+\s*/
.
"This is a sentence."
0: This
1: This
2: This
3: This
4:
5: is
6: is
7:
8: a
9:
10: sentence.
// ...
18: sentence.
, :
0: This
1: This
2: This
3: This
4: This
5: is
6: is
7: is
8: a
9: a
10: sentence.
// ...
18: sentence.